Code Explanation:
1. Defining a Custom Metaclass
class Meta(type):
Meta is a metaclass because it inherits from type.
A metaclass controls how classes are created.
2. Overriding the Metaclass __new__ Method
def __new__(cls, name, bases, dct):
dct["x"] = 10
return super().__new__(cls, name, bases, dct)
This method runs when a class is being created.
Parameters:
cls → the metaclass (Meta)
name → name of the class being created ("A")
bases → parent classes
dct → dictionary of attributes defined inside the class
What it does:
Adds a new class attribute x = 10 into the class dictionary.
Then calls type.__new__ to create the actual class.
So every class created with this metaclass automatically gets x = 10.
3. Creating Class A Using the Metaclass
class A(metaclass=Meta):
pass
What happens internally:
Python sees metaclass=Meta.
Calls:
Meta.__new__(Meta, "A", (), {})
Inside __new__, x = 10 is injected.
Class A is created with attribute x.
So effectively, Python turns it into:
class A:
x = 10
4. Accessing the Injected Attribute
print(A.x)
A.x looks for attribute x in class A.
It finds x = 10 (injected by the metaclass).
Prints 10.
5. Final Output
10
Final Answer
✔ Output:
10


0 Comments:
Post a Comment