Constructor in Python

Sharing

Click to Home

Log Issues

Click to Log Issue

Description:

What is class definition and is usually called init (with two underscores on either side). When you create an object of the class, the constructor method is automatically called to initialize the object.
 

class MyClass:
    def __init__(self):
        self.x = 10

obj = MyClass()

 

In this example, the constructor method __init__ is called when the object obj is created. The constructor initializes the object's x attribute to 10.

Constructors are useful for initializing the attributes of an object when it is created. They can also be used to perform any other necessary setup or initialization tasks.


Click to Home