AttributeError的:int对象有没有属性

问题描述:

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)指向列表。您的代码现在不支持这两种操作。第一个可能会实施(但实际上不应该),第二个可能不会。 –

首先,我不能重现您显示的确切错误,但我认为这是某种“错字”。您试图将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") 

您可能使用逗号而不是加号。看看

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))