Code Explanation:
1. Defining a Custom Metaclass
class AutoID(type):
AutoID is a metaclass because it inherits from type.
A metaclass controls how classes are created.
2. Defining a Class-Level Counter
counter = 0
counter is a class variable of the metaclass.
It is shared across all classes created using AutoID.
3. Overriding the Metaclass __new__ Method
def __new__(cls, name, bases, dct):
dct["id"] = cls.counter
cls.counter += 1
return super().__new__(cls, name, bases, dct)
__new__ is called whenever a class using this metaclass is created.
Parameters:
cls → the metaclass (AutoID)
name → name of the class being created
bases → base classes
dct → class attributes
What it does:
Inserts an attribute id into the class dictionary with the current counter value.
Increments the counter for the next class.
Creates the class normally.
4. Creating Class A
class A(metaclass=AutoID): pass
Triggers AutoID.__new__(..., "A", ...)
counter is 0, so:
A.id = 0
Then counter becomes 1.
5. Creating Class B
class B(metaclass=AutoID): pass
Triggers AutoID.__new__(..., "B", ...)
counter is now 1, so:
B.id = 1
Then counter becomes 2.
6. Printing the IDs
print(A.id, B.id)
Prints the class attributes id of A and B.
7. Final Output
0 1


0 Comments:
Post a Comment