Code Explanation:
1️⃣ Defining a Metaclass
class Meta(type):
Explanation
Meta is a metaclass.
A metaclass is used to control how classes are created.
By default, Python uses type to create classes.
Here, we customize that process.
2️⃣ Overriding __new__
def __new__(cls, name, bases, d):
Explanation
__new__ is called when a class is being created.
Parameters:
cls → the metaclass (Meta)
name → name of class (A)
bases → parent classes
d → dictionary of class attributes
3️⃣ Modifying Class Attributes
d['x'] = 100
Explanation
Adds a new attribute x to the class.
This happens before the class is actually created.
So every class using this metaclass will have:
x = 100
4️⃣ Creating the Class
return super().__new__(cls, name, bases, d)
Explanation
Calls the original type.__new__() method.
Actually creates the class A with updated attributes.
Returns the newly created class.
5️⃣ Defining Class with Metaclass
class A(metaclass=Meta):
Explanation
Class A is created using Meta.
So Meta.__new__() runs automatically.
It injects x = 100 into class A.
6️⃣ Empty Class Body
pass
Explanation
No attributes are defined manually.
But x is already added by the metaclass.
7️⃣ Creating an Object
a = A()
Explanation
Creates an instance a of class A.
Object can access class attributes.
8️⃣ Accessing Attribute
print(a.x)
Explanation
Python looks for x:
In object → not found
In class → found (x = 100)
๐ค Final Output
100

0 Comments:
Post a Comment