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["version"] = "1.0"
return super().__new__(cls, name, bases, dct)
__new__ runs when a class using this metaclass is created.
Parameters:
cls → the metaclass (Meta)
name → name of the class being created ("App")
bases → base classes
dct → dictionary of class attributes
What it does:
Adds a new attribute version with value "1.0" into the class dictionary.
Then creates the class normally.
So every class created with Meta automatically has version = "1.0".
3. Creating Class App Using the Metaclass
class App(metaclass=Meta): pass
App is created using Meta.
During creation:
Python calls Meta.__new__(Meta, "App", (), {}).
version = "1.0" is injected.
The App class is created.
So now:
App.version == "1.0"
4. Accessing the Injected Attribute
print(App.version)
Reads the version attribute from the class App.
5. Final Output
1.0
Final Answer
✔ Output:
1.0


0 Comments:
Post a Comment