如何使用python为'in'实现自定义比较器

use*_*424 1 python

如果我有这样的课程:

class foo(object):
    def __init__(self, x, y, z):
         self.x = x
         self.y = y
         self.z = z
Run Code Online (Sandbox Code Playgroud)

在这样的列表中:

list = [foo(1, 2, 3), foo(4, 5, 6), foo(7, 8, 9)]
Run Code Online (Sandbox Code Playgroud)

我怎么能为'in'创建一个自定义测试,它只检查x和z值,这样:

new_foo = foo(1,8,3)
if new_foo in list:
    print True
else:
    print False
Run Code Online (Sandbox Code Playgroud)

会打印True

Bre*_*arn 6

使用inon列表测试使用相等,因此您需要定义一个__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))
Run Code Online (Sandbox Code Playgroud)

不过,你应该仔细考虑是否真的想要这样做.它定义了一个平等概念,适用于所有测试平等的情况.因此,如果你在帖子中做了你要求的事情,那么foo(1,2,3) == foo(1,8,3)一般情况下都是如此,而不仅仅是在使用时in.