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 __new__ Method of the Metaclass
def __new__(cls, name, bases, dct):
dct["hello"] = lambda self: "hi"
return super().__new__(cls, name, bases, dct)
__new__ runs when a class is being created.
Parameters:
cls → the metaclass (Meta)
name → name of the class being created ("A")
bases → base classes
dct → class attribute dictionary
What it does:
Adds a new method named hello into the class dictionary.
hello is a function that returns "hi".
So every class created with this metaclass will automatically get a hello() method.
3. Creating Class A Using the Metaclass
class A(metaclass=Meta): pass
Class A is created using metaclass Meta.
During creation:
Meta.__new__ is called.
hello is injected into the class.
Class A is created with method hello.
So now:
A.hello exists
4. Creating an Instance and Calling hello
print(A().hello())
A() creates an instance of A.
.hello() calls the injected method.
The lambda returns "hi".
5. Final Output
hi
Final Answer
✔ Output:
hi


0 Comments:
Post a Comment