class Point(object):
''' A point on a grid at location x, y '''
def __init__(self, x, y):
self.X=x
self.Y=y
def __str__(self):
return "X=" + str(self.X), "Y=" + str(self.Y)
def __add__(self, other):
if not isinstance(other, Point):
raise TypeError("must be of type point")
x= self.X+ other.X
y= self.Y+ other.Y
return Point(x, y)
p1= Point(5, 8)
print p1 + [10, 12]
当尝试在RHS添加列表或元组时,即打印p1 + [10,12],我正在
attributeError: int object has no attribute
如何解决这个问题?
答案 0 :(得分:3)
首先,我无法重现您显示的确切错误,但我相信这是某种错误"#34;。您正尝试将list
实例添加到Point
实例,而后者的__add__
方法会在您尝试添加非Point
的任何内容时抛出错误实例。
def __add__(self, other):
if not isinstance(other, Point):
raise TypeError("must be of type point")
你可以通过添加一些相当多的多态来克服它。
from collections import Sequence
class Point(object):
...
def _add(self, other):
x = self.X + other.X
y = self.Y + other.Y
return Point(x, y)
def __add__(self, other):
if isinstance(other, type(self)):
return self._add(other)
elif isinstance(other, Sequence) and len(other) == 2:
return self._add(type(self)(*other))
raise TypeError("must be of type point or a Sequence of length 2")
答案 1 :(得分:0)
您可以使用逗号而不是加号。看看
def __str__(self):
return "X=" + str(self.X), "Y=" + str(self.Y)
哪个应该是
def __str__(self):
return "X=" + str(self.X) + ", Y=" + str(self.Y)
至少在python3上,当我更正它时,你的代码运行得很好。显然使用print(p1 + Point(10,12))
。