python---1 发表于 2021-5-13 07:57:07

__add__问题,请帮忙

class A:
    def __init__(self,x):
      self.x = x
      
    def __add__(self,other):
      other.x = x
      return self.x + other.x

    def __radd__(self,other):
      return self.x
   
    def __iadd__(self,other):
      return self.x + other.x-2
   
   
>>> a = A(42)
>>> b = A(3)
>>> a+b
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
    a+b
File "D:\2pythonproject\lei类__add__等运算.py", line 6, in __add__
    other.x = x
NameError: name 'x' is not defined
为什么啊

wp231957 发表于 2021-5-13 08:55:21

def __add__(self,other):
      other.x = x
      return self.x + other.x
这里哪有x 啊人家提示x没定义,没毛病啊

python---1 发表于 2021-5-13 09:44:45

谢谢,已明白,删掉 other.x = x
页: [1]
查看完整版本: __add__问题,请帮忙