Distinguish Metaclass Calls from Class Construction
Core idea
Two levels of construction are involved. A metaclass new creates a class object; its init initializes that class. Calling the resulting class normally invokes the metaclass call, which delegates to the class new and, if a suitable instance is returned, init. A metaclass can intercept instance calls, but should usually delegate through super().call(*args, **kwargs) to preserve the construction contract.
class Meta(type): def __new__(mcls, name, bases, ns): print('class', name) return super().__new__(mcls, name, bases, ns) def __call__(cls, *args, **kwargs): print('call', cls.__name__) return super().__call__(*args, **kwargs)class Meter(metaclass=Meta): def __new__(cls, value): print('allocate') return super().__new__(cls) def __init__(self, value): print('initialize') self.value = valuem = Meter(7)print(m.value)Class creation occurs once at definition. Calling Meter uses Meta.call, which delegates allocation and initialization.
Count successful instance constructions
class CountMeta(type): def __init__(cls, name, bases, ns): super().__init__(name, bases, ns) cls.created = 0 def __call__(cls, *args, **kwargs): obj = super().__call__(*args, **kwargs) cls.created += 1 return objclass Job(metaclass=CountMeta): def __init__(self, size): if size <= 0: raise ValueError('size') self.size = sizeJob(2)try: Job(0)except ValueError: passJob(3)print(Job.created)The counter increases only after successful delegated calls. It is a teaching example, not a thread-safe metrics implementation.
Common mistake
Do not call cls(*args, **kwargs) inside its metaclass call; it re-enters the hook. Do not manually call init after super().call, which normally already initializes the instance.
Practice
Create a subclass of Job and verify its successful constructions increment its own count rather than the parent count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Metaclass call and construction
Check your understanding of metaclass call and construction.
What is printed?
class M(type): def __call__(cls): print('call'); return super().__call__()class C(metaclass=M): passprint(type(C()).__name__)What is printed?
class C: def __new__(cls): return 5 def __init__(self): print('init')print(C())Which hook intercepts ordinary calls to a class governed by a metaclass?
Why delegate through super().__call__?