Mikil 发表于 2020-10-16 17:03:44

python 中add魔法方法重写

class A(int):
    def __add__(self, other):
      return int.__add__(self, other)
    def __sub__(self, other):
      return int.__sub__(self, other)

重写int方法时,上面是正确的,但是下面却是错误的

class A(int):
    def __add__(self, other):
      return super().__add__(self, other)
    def __sub__(self, other):
      return super().__sub__(self, other)

a = A(2)
b = A(3)

a + b

TypeError: expected 1 arguments, got 2

为什么不能使用super呢?

lirenbing01 发表于 2020-10-16 17:13:38

super() 函数是用于调用父类的
比如这样
class B(int):
    def __add__(self, other):
      return int.__add__(self, other)

    def __sub__(self, other):
      return int.__sub__(self, other)


class A(B):
    def __add__(self, other):
      return super().__add__(other)

    def __sub__(self, other):
      return super().__sub__(other)


if __name__ == '__main__':
    a = A(2)
    b = A(3)

    print(a + b)

hrp 发表于 2020-10-16 17:18:33

本帖最后由 hrp 于 2020-10-16 17:31 编辑

class A(int):
    def __add__(self, other):
      return super().__add__(other)
    def __sub__(self, other):
      return super().__sub__(other)
      
a=A(2)
b=A(3)
print(a+b)
页: [1]
查看完整版本: python 中add魔法方法重写