0

How can I check if an object is in another object? So say I have the following defined:

class Container:
    def __init__(self):
        self.a = ['x','y','z']

and I want to be able to make the following work:

'x' in Container()  # True

My attempt/guess was that there was some type of dunder method for in like so:

class Container:
    def __init__(self):
        self.a = ['x','y','z']
    def __in__(self, item):
        return item in self.a
petezurich
  • 9,280
  • 9
  • 43
  • 57
Marty
  • 51
  • 7

1 Answers1

-1

In this case, the in operator relies on the object being iterable. So the solution would be to define the dunder method for __iter__ as follows:

def __iter__(self, item):
    return iter(self.a)

For the final product to be:

class Container:
    def __init__(self):
        self.a = ['x','y','z']
    def __iter__(self, item):
        return iter(self.a)
Marty
  • 51
  • 7
  • 1
    The [`__iter__`](https://docs.python.org/3/reference/datamodel.html#object.__iter__) method is used for iteration and is a backup mechanism for the `in` operator. A more suitable dunder method should be [`__contains__`](https://docs.python.org/3/reference/datamodel.html#object.__contains__). Please refer to [Membership test operations](https://docs.python.org/3/reference/expressions.html#membership-test-details). – Mechanic Pig Oct 19 '22 at 06:34