Code Explanation:
๐น 1. Metaclass Definition
class Meta(type):
def __new__(cls, name, bases, dct):
dct['x'] = 100
return super().__new__(cls, name, bases, dct)
Meta is a metaclass (inherits from type)
__new__ runs when a class is being created, not an object
It receives the class attributes in dct
It modifies the class dictionary by setting:
x = 100
๐น 2. Class Creation (A)
class A(metaclass=Meta):
x = 10
Python sends this class definition to the metaclass
Internally:
Meta.__new__(Meta, 'A', (), {'x': 10})
The metaclass changes:
{'x': 10} → {'x': 100}
๐น 3. Final Class Structure
After metaclass processing, class A becomes:
class A:
x = 100
The original x = 10 is overwritten
๐น 4. Object Creation
obj = A()
Creates an instance of class A
obj itself has no x attribute
๐น 5. Attribute Lookup
print(obj.x)
Python checks:
obj → not found
class A → finds x = 100
๐น ✅ Final Output
100

0 Comments:
Post a Comment