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. Defining the __prepare__ Method
@classmethod
def __prepare__(cls, name, bases):
print("prepare", name)
return {}
__prepare__ is called before the class body is executed.
It must return a mapping (usually a dictionary) that will be used to store the class attributes.
Parameters:
cls → the metaclass (Meta)
name → name of the class being created ("A")
bases → parent classes
What it does:
Prints "prepare A"
Returns an empty dictionary {} that will be used as the class namespace.
3. Creating Class A
class A(metaclass=Meta):
x = 1
What happens internally:
Python sees metaclass=Meta.
Calls:
Meta.__prepare__("A", ())
Prints:
prepare A
The returned {} is used to execute the class body.
x = 1 is stored inside that dictionary.
After class body execution, Meta.__new__ (inherited from type) is called to create the class.
So class A is created with attribute x = 1.
4. Final Output
prepare A
(Nothing else is printed because there is no print after that.)
Final Answer
✔ Output:
prepare A


0 Comments:
Post a Comment