Python Constructors
1. Default Constructor (No Parameters)
This constructor does not take any parameters.
class Animal:
def __init__(self):
print("An Animal is created!")
a1 = Animal()
2. Parameterized Constructor
A constructor that takes arguments.
class Car:
def __init__(self, brand, model):
[Link] = brand
[Link] = model
c1 = Car("Toyota", "Corolla")
print([Link], [Link]) # Toyota Corolla
3. Constructor With Default Values
Setting default values for constructor parameters.
class Employee:
def __init__(self, name="Unknown", salary=3000):
[Link] = name
[Link] = salary
e1 = Employee()
e2 = Employee("John", 5000)
print([Link], [Link]) # Unknown 3000
print([Link], [Link]) # John 5000
4. Constructor With Validation
Adding validation inside the constructor.
class Student:
def __init__(self, name, age):
if age < 0:
raise ValueError("Age cannot be negative!")
[Link] = name
[Link] = age
s1 = Student("Alice", 20)
5. Constructor in Inheritance
Using a parent class constructor in a subclass.
class Animal:
def __init__(self, species):
[Link] = species
class Dog(Animal):
def __init__(self, name, breed):
super().__init__("Dog")
[Link] = name
[Link] = breed
d1 = Dog("Buddy", "Golden Retriever")
print([Link], [Link], [Link])