GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Python __init_subclass__ Method - Complete Guide Python __init_subclass__ MethodLast modified April 8, 2025
This comprehensive guide explores Python's Basic Definitions
The Key characteristics: it's a class method (but doesn't need decorator), receives the subclass as argument, and runs during class definition. Introduced in Python 3.6 as a simpler alternative to metaclasses for many use cases. Basic __init_subclass__ Implementation
Here's the simplest implementation showing how basic_init_subclass.py
class Base:
def __init_subclass__(cls, **kwargs):
print(f"Subclass {cls.__name__} created")
super().__init_subclass__(**kwargs)
class Child(Base):
pass
# Output: "Subclass Child created"
This example shows the basic pattern. When Child inherits from Base,
The Class Registration Pattern
registration.py
class PluginRegistry:
plugins = []
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
PluginRegistry.plugins.append(cls)
class PluginA(PluginRegistry):
pass
class PluginB(PluginRegistry):
pass
print(PluginRegistry.plugins) # [<class '__main__.PluginA'>, <class '__main__.PluginB'>]
This implementation automatically collects all plugin classes that inherit from PluginRegistry. The registry can then be used to instantiate or inspect plugins. This pattern is useful for plugin systems where you want to discover all available implementations without explicitly registering them. Adding Class Attributes
add_attributes.py
class Document:
def __init_subclass__(cls, doc_type=None, **kwargs):
super().__init_subclass__(**kwargs)
if doc_type is not None:
cls.doc_type = doc_type
class PDF(Document, doc_type="application/pdf"):
pass
class Word(Document, doc_type="application/msword"):
pass
print(PDF.doc_type) # "application/pdf"
print(Word.doc_type) # "application/msword"
This example shows how to add type information to document classes. The
The method checks for the parameter and adds it as a class attribute if present. This pattern is useful for declarative class definitions. Subclass Validation
validation.py
class Shape:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if not hasattr(cls, 'area'):
raise TypeError(f"Subclass {cls.__name__} must implement 'area' method")
class Circle(Shape):
def area(self):
return 3.14 * self.radius ** 2
# class Square(Shape): # Would raise TypeError
# pass
This implementation ensures all Shape subclasses implement an This is more maintainable than checking at runtime and provides clearer error messages during development. Plugin System with Configuration
A more advanced plugin system can use plugin_system.py
class PluginSystem:
_plugins = {}
def __init_subclass__(cls, name=None, **kwargs):
super().__init_subclass__(**kwargs)
if name is None:
name = cls.__name__.lower()
if name in PluginSystem._plugins:
raise ValueError(f"Plugin {name} already exists")
PluginSystem._plugins[name] = cls
@classmethod
def get_plugin(cls, name):
return cls._plugins.get(name)
class DatabasePlugin(PluginSystem, name="db"):
pass
class CachePlugin(PluginSystem, name="cache"):
pass
print(PluginSystem.get_plugin("db")) # <class '__main__.DatabasePlugin'>
This implementation adds named registration and duplicate prevention. Plugins must provide unique names, which are used to retrieve them later.
The system demonstrates how Best Practices
Source ReferencesAuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Python tutorials. |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |