2016-07-06 202 views
0
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對象有沒有屬性

attributeError: int object has no attribute 

這又如何解決?

+0

我得到TypeError(「必須是類型點」)。因爲你要添加一個點以外的類型,所以要點。這正是你告訴你的代碼要做的事情,這有什麼問題? –

+0

你不加分。 '[10,12]'顯然不等於'點(10,12)'。您正在添加a)列表,b)指向列表。您的代碼現在不支持這兩種操作。第一個可能會實施(但實際上不應該),第二個可能不會。 –

回答

3

首先,我不能重現您顯示的確切錯誤,但我認爲這是某種「錯字」。您試圖將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") 
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))

相關問題