w3resource

When is the constructor called during object creation in Python?

Python constructor invocation

The constructor, represented by the '__init__()' method in Python, is automatically called during object creation. Specifically, the constructor is invoked when an instance of a class is created. Python calls the constructor method internally when you create an object using a class name followed by parentheses.

Example:

class Student:
    def __init__(self):
        print("Constructor called.")

Now, create an instance of this class:

obj = MyClass()

Program will call the __init__() method, display the message:

Constructor called.

During object creation, the '__init()__' method is automatically called, and any code within the constructor is executed. The constructor allows you to perform any necessary setup or initialization tasks, such as defining attributes or configuring the object's initial state. This is before the object is ready for use.



Follow us on Facebook and Twitter for latest update.