【发布时间】:2016-11-10 15:04:34
【问题描述】:
我正在尝试制作一个程序来使用__add __添加向量:
class vects:
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self, vect):
total_x = self.x + vect.x
total_y = self.y + vect.y
return vects(total_x, total_y)
plusv1 = vects.__add__(2,5)
plusv2 = vects.__add__(1,7)
totalplus = plusv1 + plusv2
产生的错误如下:
line 12, in <module> plusv1 = vects.__add__(2,5)
line 7, in __add__ total_x = self.x + vect.x
AttributeError: 'int' object has no attribute 'x'
【问题讨论】:
-
根据我对您的代码的理解,您正在使用的函数应按如下方式使用:
vects.__add__(vects(2, 5))而不是vects.__add__(2, 5),因为 add 定义正在等待只有 1 个参数,这似乎是 vects 类的另一个实例
标签: python class python-3.x