Python Classes

Python __init__ Method

Constructor method

Python __init__ Method

The __init__() method is a special method in Python classes. It is called automatically when an object is created from a class.

Understanding __init__

The __init__() method is used to initialize the object's attributes:

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

Default Values

You can provide default values for parameters:

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

person1 = Person("Bob")
print(person1.age)  # Output: 18