__init_subclass__ in Python



In Python __init_subclass__ method is a special method that allows us to initialize or customization of class creation particularly for subclasses.

Key Characteristics of __init_subclass__

Some of the Key aspects of '__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: 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, it 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

Output

Subclass created: SubClass1
Subclass created: SubClass2

Customizing Subclasses

By using __init_subclass__ method we can customize the creation of subclasses.

Example

The below example code defines we can require that all subclasses have a certain attribute, but if we try to create a subclass without the required_attribute, 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

# This will raise a TypeError because 'required_method' is not implemented
class SubClass2(Base):
    pass  

Output

TypeError: SubClass2 must implement 'required_method'.
Updated on: 2024-11-13T13:49:50+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements