元类哈希,__ eq__和isinstance

时间:2019-12-21 11:04:39

标签: python-3.x abstract-class metaclass isinstance

我已经实现了一个类及其元类,都定义了包括__eq____hash__在内的二进制dunder方法。元类的__eq__方法应该简单地实例化该类,然后将比较结果传递给类运算符。但是,当我在类上使用isinstance时,由于isinstance似乎正在调用元类的__eq__方法而又调用了类的{{1} }方法,再次调用__eq__

isinstance

这是python3.6.7中对我的结果:

from abc import ABCMeta

class Metaclass(ABCMeta):
    def __eq__(cls, other):
        return cls() == other

    def __hash__(cls):
        return 0 #would be implemented accordingly with a correct hastype

class Myclass(metaclass=Metaclass):
    def __eq__(self, other):
        if isinstance(other, Myclass):
            """dostuff"""
        else:
            return NotImplemented

class Childclass(Myclass): pass

isinstance(Childclass, Myclass)

1 个答案:

答案 0 :(得分:1)

isinstance(Childclass, Myclass)

永远不会做您想做的事情,因为isinstance接受类的实例而不是类本身。

瞧,如果实例化Childclass,则此调用成功。

isinstance(Childclass(), Myclass) # => True

我刚刚运行了此程序,但看不到错误。运行Python 3.7.5。

In [35]: from abc import ABCMeta
    ...:
    ...: class Metaclass(ABCMeta):
    ...:     def __eq__(cls, other):
    ...:         return cls() == other
    ...:
    ...:     def __hash__(cls):
    ...:         return 0 #would be implemented accordingly with a correct hastype
    ...:
    ...: class Myclass(metaclass=Metaclass):
    ...:     def __eq__(self, other):
    ...:         if isinstance(other, Myclass):
    ...:             """dostuff"""
    ...:         else:
    ...:             return NotImplemented
    ...:
    ...: class Childclass(Myclass): pass
    ...:

In [36]: isinstance(Childclass, Myclass)
Out[36]: False
相关问题