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]

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

attributeError: int object has no attribute

How can this problem be solved?

2
  • I get TypeError("must be of type point"). Because you're adding a type other than a point, to the point. That's exactly what you told your code to do, what's the issue? Commented Jul 6, 2016 at 18:38
  • You are not adding points. [10, 12] clearly does not equal Point(10,12). You are adding a) list to point, b) point to list. Both operations are not supported by your code right now. first one may potentially be implemented (but really shouldn't), second may not. Commented Jul 6, 2016 at 18:40

2 Answers 2

3

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")
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.