如果我有这样的类(class):
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
请您参考如下方法:
在使用相等性的列表测试中使用 in,因此您需要定义一个 __eq__ 方法:参见 the documentation .您还需要定义一个 __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) 通常为真,而不仅仅是在使用 在。
