我已经实现了一个类及其元类,都定义了包括__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)
答案 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