1

如果我有这样的课:

class foo(object):
    def __init__(self, x, y, z):
         self.x = x
         self.y = y
         self.z = z

在这样的列表中:

list = [foo(1, 2, 3), foo(4, 5, 6), foo(7, 8, 9)]

我如何为“in”创建一个自定义测试,以便它只检查 x 和 z 值,这样:

new_foo = foo(1,8,3)
if new_foo in list:
    print True
else:
    print False

将打印 True

4

1 回答 1

6

在列表上使用in相等性测试,因此您需要定义一个__eq__方法:请参阅文档。您还需要定义一种__hash__方法,以确保您的对象在具有可变状态时以一致的方式比较相等。例如:

class foo(object):
    def __init__(self, x,y,z):
         self.x = x
         self.y = y
         self.z = z

    def __eq__(self, other):
        return (self.x, self.z) == (other.x, other.z)

    def __hash__(self):
        return hash((self.x, self.z))

不过,您应该仔细考虑是否真的要这样做。它定义了一个平等的概念,适用于所有测试平等的情况。因此,如果您按照帖子中的要求进行操作,那么foo(1,2,3) == foo(1,8,3)一般来说都是正确的,而不仅仅是在使用in.

于 2012-07-20T06:30:46.767 回答