繁体   English   中英

AttributeError:int对象没有属性

[英]AttributeError : int object has no attribute

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

如何解决这个问题?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM