Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
__init_subclass__ in Python
In Python, the __init_subclass__ method is a special method that allows us to initialize or customize class creation, particularly for subclasses.
Key Characteristics of __init_subclass__
Some of the key aspects of the __init_subclass__ method are as follows:
-
Automatic Invocation: The __init_subclass__ method is automatically called during the creation of a subclass and no need to manually invoke this method.
-
Customizable via Parameters: To pass additional information or configuration options during subclass creation, this method can accept keyword arguments.
-
Inheritance and Overriding: Python's __init_subclass__ function provides a way of customization and control of subclass generation through inheritance and overriding.
-
Enforcing Constraints: We can enforce specific requirements on the subclasses when they are defined by enforcing the constraints in this __init_subclass__ function.
Defining __init_subclass__
To define __init_subclass__ inside a class is done just like any other method, but it should have cls as its first parameter, which refers to the class that is being created (the subclass).
Example
class Base:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
print(f"Creating subclass: {cls.__name__}")
Working of __init_subclass__
The __init_subclass__ method is automatically called when you define a new class that inherits from the Base class or parent class.
Example
In the below example SubClass1 and SubClass2 are created as subclasses of Base, then the __init_subclass__ method is triggered ?
class Base:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
print(f'Subclass created: {cls.__name__}')
class SubClass1(Base):
pass
class SubClass2(Base):
pass
Subclass created: SubClass1 Subclass created: SubClass2
Customizing Subclasses
By using the __init_subclass__ method we can customize the creation of subclasses.
Example
The below example shows how we can require that all subclasses have a certain method. If we try to create a subclass without the required_method, it will raise a TypeError ?
class Base:
# This method is automatically called when a subclass is defined
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if not hasattr(cls, 'required_method'):
raise TypeError(f"{cls.__name__} must implement 'required_method'.")
# SubClass1 implements 'required_method'
class SubClass1(Base):
def required_method(self):
pass
print("SubClass1 created successfully")
# This will raise a TypeError because 'required_method' is not implemented
try:
class SubClass2(Base):
pass
except TypeError as e:
print(f"Error: {e}")
SubClass1 created successfully Error: SubClass2 must implement 'required_method'.
Using Keyword Arguments
The __init_subclass__ method can accept keyword arguments to customize subclass behavior ?
class Vehicle:
def __init_subclass__(cls, wheels=4, **kwargs):
super().__init_subclass__(**kwargs)
cls.wheels = wheels
print(f"{cls.__name__} has {wheels} wheels")
class Car(Vehicle):
pass
class Bicycle(Vehicle, wheels=2):
pass
class Truck(Vehicle, wheels=6):
pass
print(f"Car wheels: {Car.wheels}")
print(f"Bicycle wheels: {Bicycle.wheels}")
print(f"Truck wheels: {Truck.wheels}")
Car has 4 wheels Bicycle has 2 wheels Truck has 6 wheels Car wheels: 4 Bicycle wheels: 2 Truck wheels: 6
Conclusion
The __init_subclass__ method provides a powerful way to customize and control subclass creation in Python. It's automatically called when subclasses are defined and can enforce constraints, add attributes, or perform custom initialization logic.
