Code Explanation:
1. Defining the Metaclass
class Meta(type):
type is the default metaclass in Python.
By inheriting from type, Meta becomes a custom metaclass.
A metaclass controls how classes themselves are created.
๐ Normal class → creates objects
๐ Metaclass → creates classes
๐น 2. Overriding __new__ in the Metaclass
def __new__(cls, name, bases, dct):
This method is called when a class is being created, not when an object is created.
Parameters:
cls → the metaclass (Meta)
name → class name being created ("Test")
bases → parent classes (())
dct → class namespace dictionary ({} initially)
๐น 3. Injecting a Method into the Class
dct["greet"] = lambda self: "Hello"
A new method named greet is dynamically added to the class.
lambda self: "Hello" acts like:
def greet(self):
return "Hello"
This method becomes part of every class created using Meta.
๐น 4. Creating the Class Object
return super().__new__(cls, name, bases, dct)
Calls type.__new__() to actually create the class
Uses the modified dictionary (now containing greet)
Returns the new class object → Test
๐ At this point, Test already has a greet() method.
๐น 5. Defining the Class Using the Metaclass
class Test(metaclass=Meta):
pass
Python sees metaclass=Meta
Instead of using type, it uses Meta
This triggers:
Meta.__new__(Meta, "Test", (), {})
➡️ greet() gets injected into Test
๐น 6. Creating an Object of the Class
Test()
A normal object is created
No __init__ method exists, so nothing special happens
The object inherits greet() from the class
๐น 7. Calling the Injected Method
print(Test().greet())
Step-by-step:
Test() → creates an instance
.greet() → found in the class (added by metaclass)
self → instance of Test
Returns "Hello"
✅ Final Output
Hello

0 Comments:
Post a Comment