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.
Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.
Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object. For example, isinstance(x, int) to check if x is an instance of a class int .
Using the zip() function we can create a list of tuples from n lists.
if not isinstance(someVariable, str): .... You are simply negating the "truth value" (ie Boolean) that isinstance is returning.
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)
As simple as error you got says: the list object in python (or probably in any language does not have x or y attributes). You must handle list (and tuple also) case separately
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With