The Python __main__ entry point
Or more formally:
The Python “main guard”
This Is Important
It allows one file to have two behaviors:
-
Behave like a program
Runmain()when executed from terminal. -
Behave like a library
Provide classes, functions, etc. when imported.
Example:
Output will run main().
But:
Will NOT run main — only the classes become available.
import math
class Vector2D:
def __init__(self, x, y):
# store values inside the object
self.x = x
self.y = y
def length(self):
# compute vector magnitude
return math.sqrt(self.x*self.x + self.y*self.y)
def add(self, other):
# add two vectors
return Vector2D(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector2D({self.x}, {self.y})"
############################################################
# MAIN FUNCTION
############################################################
def main():
print("=== Vector2D Demo ===")
v1 = Vector2D(3, 4)
v2 = Vector2D(1, 2)
print("v1 =", v1)
print("v2 =", v2)
print("Length of v1:", v1.length())
print("Length of v2:", v2.length())
v3 = v1.add(v2)
print("v1 + v2 =", v3)
print("=== END ===")
############################################################
# RUN MAIN ONLY IF FILE EXECUTED DIRECTLY
############################################################
if __name__ == "__main__":
main()
Explanation
1. Class definition
A 2D vector with x and y.
2. __init__ and self
self stores data inside the object.
3. Methods use self and other
self is the object before the dot.other is the object passed into the method.
4. main() function
Python will run this like a normal program.
5. Program entry point
Means “run main() only if this file is executed directly”.
If you want, I can now give:
Next Level Example:
A class with inheritance (Animal → Dog → Cat),
or an AI-oriented example (Matrix class, Layer class, Neuron class, etc.)
Tell me which direction you prefer.