我尝试的是使用singledispatch重载Posicion类中的函数,并尝试遵循OOP:
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, y, 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])
return (other[0].upper(), other[1]) == self.get_posicion()
if __name__ == "__main__":
Posicion('a', 1) == ('a', 1)
但是它总是在@__eq__.register(_Posicion)
中输入,如果我删除了它,它总是在def __eq__(self, other):
中输入
我再次为这个问题的措辞可能不好而道歉,并提前感谢您的帮助。如果有任何其他信息,我应该补充,请让我知道
我会混合使用duck类型和单一分派
这稍微削弱了您的尝试:我们不坚持比较两个
Posicion
实例,而是允许将Posicion
与实现可调用get_posicion
属性的任何对象进行比较。如果失败,只需基于对象标识进行比较,否则调用两个对象的方法并比较结果我们检查的唯一显式类型是
tuple
,避免了在类定义本身中有对Posicion
的真正引用。(如果您愿意,您可以在中安全地检查isinstance(other, Posicion)
对__eq__
的定义;正如singledispatchmethod
的一个参数Posicion
尚未定义一样。)相关问题 更多 >
编程相关推荐