Home » Posts tagged 'Python constructor chaining'

Tag Archives: Python constructor chaining

Newly Updated Posts

Python Constructors

In this tutorial, we are going to learn Contructors in Python

In Python, a constructor is a special method that is automatically called when an object of a class is created. Constructors are used to initialize the attributes (properties) of an object. In Python, the constructor method is named __init__().

Here’s an example of a simple constructor in Python:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person1 = Person("Alice", 25)
print(person1.name)  # Output: Alice
print(person1.age)   # Output: 25

In the example above, we define a class called Person. The __init__() method takes three parameters: self, name, and age. The self parameter refers to the instance of the class, and it is automatically passed when an object is created. The name and age parameters are used to initialize the name and age attributes of the object.

When we create an instance of the Person class using the Person("Alice", 25) syntax, the __init__() method is automatically called with the provided arguments. The name and age attributes of the object are then initialized with the corresponding values.

You can also define default values for the constructor parameters, making them optional:

class Person:
    def __init__(self, name=None, age=None):
        self.name = name
        self.age = age

person1 = Person("Alice")
person2 = Person(age=25)
person3 = Person()

print(person1.name, person1.age)  # Output: Alice None
print(person2.name, person2.age)  # Output: None 25
print(person3.name, person3.age)  # Output: None None

In this example, we can create instances of the Person class with different combinations of provided arguments or no arguments at all. The attributes name and age will be initialized accordingly, with None as the default value if no argument is provided.

Remember that the self parameter is always required in the constructor method to refer to the instance being created.