smithdoto smithdoto - 5 months ago 21
Python Question

Implementing Tuples and Lists in the isinstance Function in Python 2.7

I am trying to accept

tuple
and
list
as object types in an
__add__
method in Python. Please see the following code:

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, list, tuple)):
raise TypeError("Must be of type Point, list, or tuple")
x = self.X + other.X
y = self.Y + other.Y
return Point(x, y)

p1 = Point(5, 10)

print p1 + [3.5, 6]


The error I get when running it in the Python interpreter is:

AttributeError: 'list' object has no attribute 'X'


I simply cannot figure our why this isn't working. This is homework for a college course and I have very little experience with Python. I know that the
isinstance
function in Python can accept a tuple of type objects, so I am not sure what element I am missing for
tuple
and
list
objects to be accepted. I feel like this is something really simple I am just not picking up on.

Answer

If you want to be able to add lists or tuples, change your add method:

def __add__(self, other):
    if not isinstance(other, (Point, list, tuple)):
        raise TypeError("Must be of type Point, list, or tuple")
    if isinstance(other, (list, tuple)):
        other = Point(other[0], other[1])
    x = self.X + other.X
    y = self.Y + other.Y
    return Point(x, y)

Otherwise, you'd have to add another Point object, not a list. In that case, just tweak your last line:

print p1 + Point(3.5, 6)