Code Explanation:
1) class Meta(type):
Defines a metaclass called Meta.
Since it inherits from type, it means this class is used to control how other classes are created.
Normal classes create objects.
A metaclass creates classes themselves.
2) def __new__(cls, name, bases, dct):
__new__ is called when a new class (not object) is being created.
Parameters:
cls → the metaclass itself (Meta).
name → name of the class being defined (e.g., "A").
bases → tuple of base classes for inheritance.
dct → dictionary of attributes and methods defined in the class body.
3) dct['id'] = 100
Before the class is created, we inject a new class attribute id into its dictionary.
This means every class using this metaclass will automatically have id = 100.
4) return super().__new__(cls, name, bases, dct)
Calls the parent (type.__new__) to actually create the class with the modified dictionary.
Without this, the class A would not be created.
5) class A(metaclass=Meta):
Defines a new class A.
Instead of the default type metaclass, it uses our custom Meta.
When Python sees this, it calls Meta.__new__ to create A.
Inside Meta.__new__, id = 100 is added.
6) print(A.id)
Since the metaclass injected id = 100, class A has a class attribute id.
Prints:
100
Final Output
100
.png)

0 Comments:
Post a Comment