简体   繁体   中英

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]

When trying to add list or tuple at RHS ie print p1 + [10, 12], I'm getting

attributeError: int object has no attribute

How can this problem be solved?

First of all I can't reproduce the exact error you show, but I believe that is some sort of a "typo". You are trying to add a list instance to a Point instance, while the __add__ method of the later throws the error whenever you try to add anything that is not a Point instance.

def __add__(self, other):
    if not isinstance(other, Point):
        raise TypeError("must be of type point")

You could possibly overcome it by adding a fair bit of polymorphism.

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

You may have a comma instead of a plus. Look at

def __str__(self):
    return "X=" + str(self.X), "Y=" + str(self.Y)

Which should be

def __str__(self):
    return "X=" + str(self.X) + ", Y=" + str(self.Y)

At least on python3 when I correct it your code runs nicely. Obviously using print(p1 + Point(10,12)) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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