class method __instancecheck__ does not work

后端 未结 2 1524
有刺的猬
有刺的猬 2020-12-10 03:27

I am using python 2.7.3 on Windows. I tried to override the __instancecheck__ magic method as a class method. But I can not make it work.

class          


        
2条回答
  •  鱼传尺愫
    2020-12-10 04:11

    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!

提交回复
热议问题