In Python, a constructor is a special method used to initialize an object when it is created. This method is called automatically when a new instance of a class is instantiated. Constructors are defined using the init method.
Key Characteristics of Constructors:
Constructor Syntax
class MyClass:
def __init__(self, arg1, arg2):
self.attribute1 = arg1
self.attribute2 = arg2
# Create an object of MyClass
obj = MyClass("value1", "value2")
# Access attributes
print(obj.attribute1) # Output: value1
print(obj.attribute2) # Output: value2
Types of Constructors
Default Constructor: A constructor that does not take any arguments (except self).
class MyClass:
def __init__(self):
self.name = "Default Name"
obj = MyClass()
print(obj.name) # Output: Default Name
Parameterized Constructor: A constructor that takes arguments to initialize attributes dynamically.
class MyClass:
def __init__(self, name, age):
self.name = name
self.age = age
obj = MyClass("Alice", 25)
print(obj.name) # Output: Alice
print(obj.age) # Output: 25
Example: Constructor in Action
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Creating an object of Person
person = Person("John", 30)
person.greet()
Output: Hello, my name is John and I am 30 years old.