Content · Programming · Python

Python __init_subclass__(): Customize Subclasses

Hook subclass creation using __init_subclass__().

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Hook subclass creation using __init_subclass__().

How It Works


A base class’s __init_subclass__ method runs when a derived class is defined. It can register subclasses or validate definitions without a custom metaclass.

This method runs during class definition, not per-object initialization.

Step-by-Step Example


class PluginBase:
    registered_plugins = []

    def __init_subclass__(cls, **keyword_arguments):
        super().__init_subclass__(**keyword_arguments)
        PluginBase.registered_plugins.append(cls.__name__)

class CsvPlugin(PluginBase):
    pass

print(PluginBase.registered_plugins)

Understanding the Example


  • The class groups related state and methods so each instance can manage its own values.
  • The expression '[]' supplies the value stored as 'registered_plugins'. This value is then used or checked by the later statements.

A successful run of this example prints the following output:

['CsvPlugin']

Where This Fits in a Real Program


A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.

Practice: Try It Yourself


Register two plugin subclasses and display their names.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Expecting __init_subclass__ to run every time an instance is constructed.
  • Forgetting to pass unhandled keyword arguments to super() in cooperative hierarchies.

Key Takeaways


  • Hook subclass creation using __init_subclass__().
  • A base class’s __init_subclass__ method runs when a derived class is defined.
  • This method runs during class definition, not per-object initialization.
Share this resourceSend this page to someone who may find it useful.