如何解决如何重载获取 self 类对象的 __eq__ 函数
我正在尝试使用 singledispatch 并尝试遵循 OOP 重载 Posicion 类中的这个函数:
def __eq__(self,other):
if isinstance(other,Posicion):
return other.get_posicion() == self.get_posicion()
elif type(other) == tuple:
assert len(other) == 2,"La tupla pasada por parámetro debe constar de dos elementos"
self.verificar_formato(other[0],other[1])
return (other[0].upper(),other[1]) == self.get_posicion()
我尝试从 functools 库中应用 singledispatch,但遇到了与此问题相同的错误:python3: singledispatch in class,how to dispatch self type。因为我正在尝试发送 self 类型。所以我尝试了
class _Posicion:
def __init__(self,y,x):
pass
class Posicion(_Posicion):
def __init__(self,x):
super()
self.x = x
self.y = y.upper()
def get_posicion(self):
return self.y,self.x
@singledispatch
def __eq__(self,other):
raise NotImplementedError("Everything bad")
@__eq__.register(_Posicion)
def _(self,other):
return other.get_posicion() == self.get_posicion()
@__eq__.register(tuple)
def _(self,other):
assert len(other) == 2,"La tupla pasada por parametro debe constar de dos elementos"
self.verificar_formato(other[0],other[1]) == self.get_posicion()
if __name__ == "__main__":
Posicion('a',1) == ('a',1)
但它总是输入 @__eq__.register(_Posicion)
并且如果我删除它总是输入 int def __eq__(self,other):
我再次为这个问题的措辞可能不好而道歉,并在此先感谢您的帮助。如果还有其他需要补充的信息,请告诉我。
解决方法
我会混合使用鸭子打字和单分派。
@singledispatchmethod
def __eq__(self,other):
try:
f = other.get_posicion
except AttributeError:
return (self is other) or NotImplemented
return self.get_posicion() == f()
@__eq__.register(tuple)
def _(self,other):
assert len(other) == 2,"La tupla pasada por parámetro debe constar de dos elementos"
self.verificar_formato(other[0],other[1])
return (other[0].upper(),other[1]) == self.get_posicion()
这稍微削弱了您的尝试:我们允许将 Posicion
与实现可调用 Posicion
属性的任何内容进行比较,而不是坚持比较两个 get_posicion
实例。如果失败,只根据对象身份进行比较,否则调用两个对象的方法并比较结果。
我们检查的唯一显式类型是 tuple
,避免了在类定义本身内部对 Posicion
的真实引用的需要。 (尽管如果您愿意,您可以安全地检查 isinstance(other,Posicion)
inside __eq__
的定义;它只是作为 singledispatchmethod
的参数,Posicion
是尚未定义。)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。