The short answer
Yes, in everyday use. Python programmers call __init__ the constructor, and it does the job a constructor does in C++: it runs when an object is created and sets up the object’s starting data.
Strictly speaking, Python creates an object in two steps. __new__ creates the object, and then __init__ sets it up. Because of that split, a more precise name for __init__ is initializer method.
What __init__ looks like
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
book = Book("Dune", 412) # __init__ runs here
print(book.title, book.pages)
The output is:
Dune 412
Calling Book("Dune", 412) creates a new Book object and passes it into __init__ as self, along with the two arguments. Inside __init__, self.title and self.pages are attributes that belong to that particular object.
The two steps: __new__ and __init__
When you call a class, Python first calls __new__, which creates the object and returns it. Then Python calls __init__ on that object with the arguments you passed.
Most code never writes __new__. Overriding it is uncommon and is usually reserved for special cases, such as customizing how an immutable built-in type like int or tuple is created in a subclass.
__init__ must return None. If it returns anything else, Python raises a TypeError.
The same class in C++
Here is the equivalent class in C++:
class Book {
public:
Book(std::string title, int pages) : title_(title), pages_(pages) {}
private:
std::string title_;
int pages_;
};
Several differences matter once you move between the two:
- Python passes the object explicitly as the first parameter, named
selfby convention. In C++, member functions and constructors have an implicitthispointer instead. - C++ declares the member variables in the class and sets them in a member initializer list. Python has no such list. Attributes are created by assigning them, and they can be added at any time.
- C++ allows several constructors with different parameters. Python does not allow overloading
__init__. If you define it twice in one class, the second definition replaces the first. Default arguments are the usual replacement:
class Book:
def __init__(self, title, pages=0):
self.title = title
self.pages = pages
- C++ checks constructor argument types at compile time. Python does not check argument types at all, so a wrong type shows up only when the code runs an operation that fails.
Learning C++ after Python
Many people run into this question while learning c after python. The core idea carries over: __init__ and a C++ constructor both set up a new object. The C++ rules are stricter, with compile-time type checks, a fixed set of members, and an initializer list. Those are worth learning as their own rules rather than assuming they work like __init__.