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 __new__ in the Metaclass
def __new__(cls, name, bases, dct):
return super().__new__(cls, name, (), dct)
__new__ is executed every time a class using this metaclass is created.
Instead of using the original bases, it forces bases to be empty ().
Python rule:
If no base class is provided, Python automatically inserts object.
3. Creating Class A
class A(metaclass=Meta): pass
What happens internally:
Meta.__new__ is called.
bases is replaced with ().
Python automatically inserts object.
Result:
A.__bases__ == (object,)
4. Creating Class B
class B(A): pass
Very important behavior:
B inherits the metaclass from its parent A.
So Meta.__new__ is also called for B.
Internally:
Meta.__new__(Meta, "B", (A,), {...})
The metaclass again replaces bases with ()
Python inserts object
Result:
B.__bases__ == (object,)
5. Printing the Base Classes
print(B.__bases__)
Prints the direct parent class(es) of B.
6. Final Output
(<class 'object'>,)
Final Answer
✔ Output:
(object,)

0 Comments:
Post a Comment