如何重载获取self类对象的_ueq__;函数

2024-10-05 14:23:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试的是使用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):中输入

我再次为这个问题的措辞可能不好而道歉,并提前感谢您的帮助。如果有任何其他信息,我应该补充,请让我知道


Tags: selfregistergetreturnifdeftypeupper
1条回答
网友
1楼 · 发布于 2024-10-05 14:23:23

我会混合使用duck类型和单一分派

@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)__eq__的定义;正如singledispatchmethod的一个参数Posicion尚未定义一样。)

相关问题 更多 >