A constructor is a special method used to initialize objects. In Python, the constructor method is __init__
.
Types of Constructors
- Default Constructor:
A constructor that takes no parameters (other than self
) and usually assigns default values.
class Person:
def __init__(self):
self.name = "Default Name"
person1 = Person()
print(person1.name) # Output: Default Name
- Parameterized Constructor:
A constructor that accepts arguments to initialize attributes dynamically.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 25)
print(person1.name, person1.age) # Output: Alice 25
👉 Next tutorial: Python Inheritance