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["hello"] = lambda self: "hi"
return super().__new__(cls, name, bases, dct)
This method runs whenever a class using this metaclass is created.
Parameters:
cls → the metaclass (Meta)
name → name of the class being created ("A")
bases → parent classes
dct → dictionary of attributes defined inside the class
What it does:
Adds a new method called hello into the class dictionary.
hello is a function that returns "hi".
Then it calls type.__new__ to actually create the class.
So every class created using Meta will automatically get a hello() method.
3. Creating Class A with the Metaclass
class A(metaclass=Meta): pass
What happens internally:
Python calls:
Meta.__new__(Meta, "A", (), {})
Inside __new__, hello is injected into A.
Class A is created with:
class A:
def hello(self):
return "hi"
4. Calling the Injected Method
print(A().hello())
A() creates an object of class A.
hello() is called on that object.
It returns "hi".
print prints "hi".
5. Final Output
hi
Final Answer
✔ Output:
hi
.png)

0 Comments:
Post a Comment