What is the __init__() Method?
The __init__() method in Python is a special constructor method that is called when an object is created from a class. Its main purpose is to initialize the object’s attributes.
Basic Syntax of __init__()
Here’s the basic syntax for the __init__() method:
MyClass: def __init__(self, param1, param2): self.attribute1 = param1 self.attribute2 = param2
- def __init__(self, param1, param2): The __init__() method takes self as its first parameter, which represents the instance of the class. Other parameters (param1, param2, etc.) are used to initialize the object’s attributes.
- self.attribute1 = param1: Initializes the attribute1 of the instance with the value of param1.
Defining the __init__() Method in a Child Class
When creating a child class, you can define its own __init__() method to initialize attributes specific to that class while also using attributes inherited from the parent class.
Define the Parent Class
First, define a parent class with its own __init__() method:
class Animal: def __init__(self, name, age): self.name = name self.age = age
- The Animal class has an __init__() method that initializes name and age.
Define the Child Class with __init__()
When defining the child class, you can add specific attributes and call the parent class’s constructor:
class Dog(Animal): def __init__(self, name, age, breed): super().__init__(name, age) # Call the parent class's constructor self.breed = breed
- super().__init__(name, age) calls the constructor of Animal to initialize name and age.
- self.breed = breed adds an attribute specific to the Dog class.
Calling the Parent Class Constructor
Using super() to call the parent class’s __init__() method is essential when the child class needs to extend or modify the initialization behavior:
Example with super()
class Animal: def __init__(self, name, age): self.name = name self.age = age class Dog(Animal): def __init__(self, name, age, breed): super().__init__(name, age) # Initialize parent class attributes self.breed = breed # Add specific attribute for Dog # Create an instance of Dog my_dog = Dog("Rex", 5, "Labrador") print(my_dog.name) # Rex print(my_dog.age) # 5 print(my_dog.breed) # Labrador
- The call to super().__init__(name, age) ensures that attributes from Animal are properly initialized.
Adding Specific Attributes in the Child Class
Child classes can add their own attributes that are not present in the parent class:
Example with Specific Attributes
class Animal: def __init__(self, name, age): self.name = name self.age = age class Dog(Animal): def __init__(self, name, age, breed, size): super().__init__(name, age) # Initialize Animal attributes self.breed = breed self.size = size # Add specific attribute for Dog # Create an instance of Dog my_dog = Dog("Rex", 5, "Labrador", "Large") print(my_dog.name) # Rex print(my_dog.age) # 5 print(my_dog.breed) # Labrador print(my_dog.size) # Large
- self.size = size is an attribute specific to the Dog class.
Redefining the __init__() Method
If the child class needs to initialize its own attributes while using those from the parent class, you should call super() to retain inherited attributes:
a. Example of Redefinition
class Animal: def __init__(self, name, age): self.name = name self.age = age class Cat(Animal): def __init__(self, name, age, color): super().__init__(name, age) # Initialize parent class attributes self.color = color # Add specific attribute for Cat def display_info(self): return f"Name: {self.name}, Age: {self.age}, Color: {self.color}" # Create an instance of Cat my_cat = Cat("Whiskers", 3, "Black") print(my_cat.display_info()) # Name: Whiskers, Age: 3, Color: Black
- display_info() is a method specific to Cat that uses inherited attributes.
Validating Data in __init__()
You can also include logic to validate data when initializing attributes:
class Animal: def __init__(self, name, age): self.name = name self.age = age class Dog(Animal): def __init__(self, name, age, breed): super().__init__(name, age) if not breed: raise ValueError("Breed cannot be empty.") self.breed = breed # Create an instance with a valid breed my_dog = Dog("Rex", 5, "Labrador") print(my_dog.breed) # Labrador # Create an instance with an invalid breed try: invalid_dog = Dog("Rex", 5, "") except ValueError as e: print(e) # Breed cannot be empty.
- Validation within __init__() ensures that breed is not empty.
Complete Example Illustrating Various Concepts
Here’s a comprehensive example that includes inheritance, overriding __init__(), and data validation:
class Vehicle: def __init__(self, brand, model): self.brand = brand self.model = model class Car(Vehicle): def __init__(self, brand, model, year, color): super().__init__(brand, model) if year < 1886: # Year of the invention of the automobile raise ValueError("Year cannot be before 1886.") self.year = year self.color = color def display_details(self): return f"Brand: {self.brand}, Model: {self.model}, Year: {self.year}, Color: {self.color}" # Create an instance of Car my_car = Car("Tesla", "Model S", 2023, "Red") print(my_car.display_details()) # Brand: Tesla, Model: Model S, Year: 2023, Color: Red # Create an instance with an invalid year try: invalid_car = Car("Ford", "T", 1800, "Black") except ValueError as e: print(e) # Year cannot be before 1886.
Key Points
- Inheritance: The child class inherits attributes and methods from the parent class.
- super(): Used to call the parent class’s constructor to initialize inherited attributes.
- Specific Attributes: Child classes can add their own attributes.
- Overriding: The __init__() method in the child class can override the parent class’s constructor while maintaining inherited functionality.
- Validation: Include validation in __init__() to ensure correct values are assigned.