Fuzzyma Fuzzyma - 19 days ago 5
Python Question

How does "in" checks for membership?

I have a multiple instances of a class. I consider two classes equal, when a certain attribute matches.
All instances are in an array

list = [a, b, c]
. I now create a new instance of said class
d
. When I do
d in list
it ofc outputs
false
.

My question is: How is membership checked when using
in
? Is it normal comparison (which means I can use
__eq__
in my class to implement the equality of classes)? If not: How can I achieve that
in
matches if a certain attribute of a class equals?

Answer
class Foo:
    def __init__(self, x):
        self.x = x
    def __eq__(self, other):
        if isinstance(other, Foo):
            return self.x == other.x

a = [1,2,3,Foo(4),Foo(5)]
Foo(5) in a
>>>True
Foo(3) in a
>>>False
Comments