Constructors
-
Master Python constructors and learn how objects are initialized using the __init__ method.
What is a Constructor?
A constructor is a special method that runs automatically when an object is created.
In Python, it is defined using __init__().Constructor Syntax
class ClassName:
def __init__(self):
# initialization code
Using Constructor
This example shows how the constructor executes automatically during object creation.
class Employee:
def __init__(self):
print("Employee object created")
obj = Employee()
Constructor with Parameters
This example initializes values using parameters passed during object creation.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def display(self):
print("Name:", self.name)
print("Salary:", self.salary)
emp1 = Employee("Anita", 45000)
emp1.display()