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["level"] = dct.get("level", 0) + 1
return super().__new__(cls, name, bases, dct)
This method runs whenever a class using this metaclass is created.
It receives:
cls → the metaclass (Meta)
name → class name ("Base", "Child")
bases → parent classes
dct → dictionary of attributes defined in the class body
What it does:
Looks for "level" in the class dictionary.
If found, it increments it by 1.
If not found, it creates "level" with value 1.
3. Creating Class Base
class Base(metaclass=Meta):
level = 1
Step-by-step:
Class body runs → dct = {"level": 1}
Meta.__new__(Meta, "Base", (), {"level": 1}) is called.
Inside __new__:
dct["level"] = 1 + 1 = 2
Class Base is created with:
Base.level = 2
4. Creating Class Child
class Child(Base):
pass
Child inherits from Base, so it also uses metaclass Meta.
Class body is empty → dct = {}
Meta.__new__(Meta, "Child", (Base,), {}) is called.
Inside __new__:
dct["level"] = 0 + 1 = 1
So:
Child.level = 1
5. Printing the Values
print(Base.level, Child.level)
Base.level is 2
Child.level is 1
6. Final Output
2 1
400 Days Python Coding Challenges with Explanation
✅ Final Answer
✔ Output:
2 1


0 Comments:
Post a Comment