Python constructor

Question

Answers ( 1 )

    0
    2024-01-11T18:05:26+00:00

    A constructor in Python is a special method used to initialize a newly created object. It is called when an object is created from a class and allows the class to initialize the attributes of the class.

    In Python, constructors are written as a method named __init__. Here is a basic example:

    class MyClass:
        def __init__(self, value):
            self.attribute = value
    
    # Creating an object of MyClass
    obj = MyClass(10)
    print(obj.attribute)  # Output: 10
    

    In this example, MyClass has a constructor __init__, which takes an additional argument value. When a new object of MyClass is created, this constructor is called to set the initial state of the object, here initializing the attribute of the object with the passed value.

    Python supports only one constructor per class. However, you can achieve multiple constructors in a way by using default arguments, class methods, or static methods.

    For example, using default arguments:

    class MyClass:
        def __init__(self, value1=0, value2=0):
            self.attribute1 = value1
            self.attribute2 = value2
    
    # Different ways to create an object
    obj1 = MyClass()
    obj2 = MyClass(20)
    obj3 = MyClass(30, 40)
    

    Each MyClass object can be created with different initial values, demonstrating the flexibility of using default arguments to simulate multiple constructors.

Leave an answer