Code Explanation:
1. Defining a Custom Metaclass
class Meta(type):
Meta is a metaclass because it inherits from type.
A metaclass controls how classes create their instances.
2. Overriding the Metaclass __call__ Method
def __call__(cls, *a, **k):
obj = super().__call__(*a, **k)
obj.ready = True
return obj
__call__ is invoked when a class is called to create an instance (Task()).
Steps:
Calls super().__call__() → creates the object normally.
Adds a new attribute ready = True to the object.
Returns the modified object.
So every object created using this metaclass automatically has ready = True.
3. Defining a Class Using the Metaclass
class Task(metaclass=Meta):
pass
Task is created using Meta as its metaclass.
Task() will invoke Meta.__call__.
4. Creating an Instance
t = Task()
This triggers:
Meta.__call__(Task)
Inside __call__:
A new Task object is created.
t.ready = True is added.
5. Checking the Attribute
print(hasattr(t, "ready"))
Checks if attribute "ready" exists on t.
Since Meta.__call__ added it, result is True.
6. Final Output
True
Final Answer
✔ Output:
True


0 Comments:
Post a Comment