1. Defining a Metaclass
class Meta(type):
A metaclass named Meta is defined.
It inherits from type, which is the default metaclass in Python.
Metaclasses control class-level behavior.
2. Overriding __instancecheck__
def __instancecheck__(cls, obj):
return obj == 1
__instancecheck__ is a special method used by isinstance().
Whenever isinstance(obj, SomeClass) is called:
SomeClass.__instancecheck__(obj)
is executed (if defined).
Here, it ignores the actual type of obj.
It returns:
True only if obj == 1
False otherwise
3. Creating a Class Using the Metaclass
class Test(metaclass=Meta): pass
A class named Test is created.
Instead of the default metaclass (type), it uses Meta.
This means Test inherits the customized __instancecheck__.
4. First isinstance Call
isinstance(1, Test)
Step-by-step:
Python detects that Test has a metaclass with __instancecheck__.
Executes:
Meta.__instancecheck__(Test, 1)
Evaluates:
1 == 1 → True
Result:
True
5. Second isinstance Call
isinstance(2, Test)
Step-by-step:
Python calls:
Meta.__instancecheck__(Test, 2)
Evaluates:
2 == 1 → False
❌ Result:
False
6. Printing the Results
print(isinstance(1, Test), isinstance(2, Test))
Prints both boolean results.
7. Final Output
True False
✅ Final Answer
✔ Output:
True False

0 Comments:
Post a Comment