简体   繁体   English

在Python 2.7中的isinstance函数中实现元组和列表

[英]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. 我正在尝试在Python的__add__方法中接受tuplelist作为对象类型。 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: 我在Python解释器中运行它时遇到的错误是:

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. 这是大学课程的家庭作业,而我对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. 我知道Python中的isinstance函数可以接受类型对象的元组,因此我不确定tuplelist对象被接受时缺少什么元素。 I feel like this is something really simple I am just not picking up on. 我觉得这很简单,我只是不了解。

If you want to be able to add lists or tuples, change your __add__ method: 如果要添加列表或元组,请更改__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)

Otherwise, you'd have to add another Point object, not a list. 否则,您将不得不添加另一个Point对象,而不是列表。 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). 您会说出这么简单的错误:python中的list对象(或者可能在任何语言中都没有x或y属性)。 You must handle list (and tuple also) case separately 您必须分别处理列表(和元组)案例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM