Code Explanation:
1. Defining a Custom Metaclass
class Meta(type):
Meta is a metaclass because it inherits from type.
Metaclasses control class-level behavior, including how isinstance() works.
2. Overriding __instancecheck__
def __instancecheck__(cls, obj):
return obj == 5
__instancecheck__ is called whenever isinstance(obj, Class) is executed.
Instead of normal type checking, it compares the object value.
It returns:
True if obj is equal to 5
False otherwise
3. Defining Class A Using the Metaclass
class A(metaclass=Meta): pass
Class A is created using the metaclass Meta.
Any isinstance(..., A) check will now use Meta.__instancecheck__.
4. Evaluating isinstance(5, A)
isinstance(5, A)
Step-by-step:
Python sees A has a custom metaclass.
Calls:
Meta.__instancecheck__(A, 5)
obj == 5 → True
5. Evaluating isinstance(3, A)
isinstance(3, A)
Step-by-step:
Calls:
Meta.__instancecheck__(A, 3)
obj == 5 → False
6. Printing the Results
print(isinstance(5, A), isinstance(3, A))
Prints the results of both checks.
7. Final Output
True False
✅ Final Answer
✔ Output:
True False

0 Comments:
Post a Comment