[英]Implementing Tuples and Lists in the isinstance Function in Python 2.7
我正在尝试在Python的__add__
方法中接受tuple
和list
作为对象类型。 请参见以下代码:
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]
我在Python解释器中运行它时遇到的错误是:
AttributeError: 'list' object has no attribute 'X'
我根本无法弄清楚为什么这不起作用。 这是大学课程的家庭作业,而我对Python的经验很少。 我知道Python中的isinstance
函数可以接受类型对象的元组,因此我不确定tuple
和list
对象被接受时缺少什么元素。 我觉得这很简单,我只是不了解。
如果要添加列表或元组,请更改__add__
方法:
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)
否则,您将不得不添加另一个Point对象,而不是列表。 在这种情况下,只需调整最后一行即可:
print p1 + Point(3.5, 6)
您会说出这么简单的错误:python中的list对象(或者可能在任何语言中都没有x或y属性)。 您必须分别处理列表(和元组)案例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.