Constructors

Learn Python constructors with examples. Understand default and parameterized constructors using the __init__ method in Python classes.

Loading...
Constructors

A constructor is a special method used to initialize objects. In Python, the constructor method is __init__.

Types of Constructors

  1. 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
  1. 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

Support my work!