instancecheck
must be defined in a metaclass:
class Enumeration(type):
def __instancecheck__(self, other):
print 'hi'
return True
class EnumInt(int):
__metaclass__ = Enumeration
print isinstance('foo', EnumInt) # prints True
Why is that? For the same reason why your second example worked. When python evaluates isinstance(A, B)
it assumes B
to be an object, looks for its class and calls __instancecheck__
on that class:
isinstance(A, B):
C = class-of(B)
return C.__instancecheck__(A)
But when B
is a class itself, then its class C
should be a class of a class, in other words, a meta-class!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…