Python Does Not Call the __instancecheck__ Method

Asked 2 years ago, Updated 2 years ago, 43 views

Python may not call the __instancecheck__ method.
Running the following code

It should be False → True
It should be False→ False
It should be False→ False
It should be False→ False

appears.
Actually, the first one should show False, but it says True.
Why isn't it called?
Thank you for your cooperation.

class Analysis (type):
    def__instancecheck__(self, other):
        return False

class SMA (metacclass=Analysis):
    pass

sma = SMA()
print('It should be False→', isinstance(sma,SMA))
print('It should be False→', isinstance(1,SMA))
print('It should be False→', isinstance([], SMA))
print('It should be False→', isinstance(', SMA))

python

2022-09-30 21:12

1 Answers

Reprinted from argus' comment.

The source code does not run __instancecheck__ because it first performs a type check and immediately returns True if the object is an instance of the specified class.Here, since sma is an instance of the SMA class, it returns True and ends.


2022-09-30 21:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.