If i had a class like this:
class foo(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
In a list like this:
list = [foo(1, 2, 3), foo(4, 5, 6), foo(7, 8, 9)]
How could i create a custom test for ‘in’ such that it checks only x and z values such that this:
new_foo = foo(1,8,3)
if new_foo in list:
print True
else:
print False
Would print True
Using
inon lists tests using equality, so you need to define an__eq__method: see the documentation. You will also need to define a__hash__method to ensure that your objects compare equal in a consistent manner if they have mutable state. For instance:You should think carefully about whether you really want to do this, though. It defines a notion of equality which will apply in all situations where equality is tested. So if you do what you ask for in your post, then
foo(1,2,3) == foo(1,8,3)will be true in general, not just when usingin.