Creating an object by calling its class, as in Point(3, 4), runs two special methods in order: __new__ creates the object, and __init__ sets it up. People often call __init__ the constructor because that is where starting values are set, but the creation step belongs to __new__. Here is how each one works, with C++ comparisons along the way.
The short answer
__new__ creates the object and returns it. __init__ then receives that object and sets its starting values. Python gives the creation step its own method. C++ has no such method on the class, so __init__ is the closest match to a C++ constructor. In C++, the memory for the object is provided first, and then the constructor runs on that memory.
__init__ sets up the object
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 4)
print(p.x, p.y) # 3 4
self is the object that already exists when __init__ runs. The method sets attributes on it and returns nothing. If __init__ returns any value other than None, Python raises a TypeError.
The C++ version does the same job with a constructor and an initializer list:
struct Point {
int x;
int y;
Point(int x_value, int y_value) : x(x_value), y(y_value) {}
};
The C++ constructor has no self parameter. The object being built is available implicitly as this inside the body.
__new__ creates the object
__new__ receives the class as its first argument, cls, and returns a new instance. You do not need to decorate it, because Python treats __new__ as a static method.
class Point:
def __new__(cls, x, y):
print("creating a Point")
return super().__new__(cls)
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 4) # prints: creating a Point
If __new__ returns something that is not an instance of the class, Python does not call __init__. Most code never writes __new__. The usual reason is subclassing an immutable built-in type such as int, str or tuple, where the value has to be set when the object is created.
The full call
Roughly, Point(3, 4) does this:
obj = Point.__new__(Point, 3, 4)
if isinstance(obj, Point):
obj.__init__(3, 4)
The real mechanism is built into the class call, but this shows the order: creation first, then initialization.
Other special names
__del__runs when Python is about to clean up an object. When that happens is not guaranteed, so it does not replace a C++ destructor. A C++ destructor runs at a known point, when a local object leaves its scope.__main__is not a method and not a constructor. It is the name Python gives a module that is run directly, which is why scripts often check__name__like this:
if __name__ == "__main__":
print("running as a script")
Is __init__ a constructor?
In the sense most C++ learners need, yes. It sets up the new object the way a constructor does. Strictly speaking, it runs after the object exists, so it is an initializer, and the creation step is __new__.
For the C++ rules, start with c class constructor, since the same ideas apply to structs as covered in c struct constructor.