__init__ — Expert Examples
Constructor; called when a new instance is created to initialize its attributes
__init__ with metaclasses
Using __init__ in metaclass-level programming.
python
# __init__ with metaclasses class AutoReprMeta(type): def __new__(mcs, name, bases, namespace): cls = super().__new__(mcs, name, bases, namespace) # Auto-generate __repr__ from __init__ params init = namespace.get("__init__") if init: import inspect params = list(inspect.signature(init).parameters.keys())[1:] def auto_repr(self): args = ", ".join(f"{p}={getattr(self, p)!r}" for p in params) return f"{type(self).__name__}({args})" cls.__repr__ = auto_repr return cls class Point(metaclass=AutoReprMeta): def __init__(self, x, y): self.x = x self.y = y class Person(metaclass=AutoReprMeta): def __init__(self, name, age): self.name = name self.age = age print(Point(3, 4)) print(Person("Alice", 30)) # MRO inspection print(f"\nMRO: {[c.__name__ for c in Point.__mro__]}")
Metaclass-level usage of __init__ lets you customize class creation and behavior at the deepest level.
Want to try these examples interactively?
Open Expert Playground