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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-interview/when-is-the-constructor-called-during-object-creation-in-python.php