Constructor

Definition

  • A constructor is a special method in Python that is used to initialize an object when it is created.

  • In Python, the constructor method is named init (short for "initialize").

  • It is automatically called when you instantiate a class using the ClassName() syntax.

Example

class Person:
    def __init__(self, name, age):
        self.name = name  # Initialize the 'name' attribute
        self.age = age    # Initialize the 'age' attribute

# Creating an instance of the Person class
person = Person("Alice", 30)
print(person.name)  # Output: Alice
print(person.age)   # Output: 30
Updated on