Implementing tuples and lists in the isinstance function in Python 2.7

I am trying to accept tuple and list as object types in the __add__ method in Python. 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] 

Error starting up in Python interpreter:

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

I just can't understand why this is not 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 tuples of type objects, so I'm not sure which element I am losing for the tuple and list objects that should be accepted. I feel that this is something very simple, I just do not type.

+8
python
source share
2 answers

If you want to add lists or tuples, change the __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 will need to add another Point object, not a list. In this case, just configure the last line:

 print p1 + Point(3.5, 6) 
+3
source share

Simpler, how did you get the error: a list object in python (or perhaps in any language does not have x or y attributes). You must also process the list (and tuple) separately.

+1
source share

All Articles