279

If I am creating my own class in Python, what function should I define so as to allow the use of the in operator, e.g.

class MyClass(object):
    ...

m = MyClass()

if 54 in m:
    ...
Neuron
  • 5,141
  • 5
  • 38
  • 59
astrofrog
  • 32,883
  • 32
  • 90
  • 131
  • I was actually searching how to override the `is` and `is not` operators. Like a `query = tinydb.Query().field == value`, to also be able to write `Query().field is not None`. But it seems I'm left with `__eq__` and `__ne__` for the time being, which leads to the unpythonic `Query().field != None`. (sarc) – Tomasz Gandor Jun 13 '17 at 11:50

3 Answers3

347

MyClass.__contains__(self, item)

Hagai
  • 678
  • 7
  • 20
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
272

A more complete answer is:

class MyClass(object):

    def __init__(self):
        self.numbers = [1,2,3,4,54]

    def __contains__(self, key):
        return key in self.numbers

Here you would get True when asking if 54 was in m:

>>> m = MyClass()
>>> 54 in m
True  

See documentation on overloading __contains__.

Neuron
  • 5,141
  • 5
  • 38
  • 59
pthulin
  • 4,001
  • 3
  • 21
  • 23
3

Another way of having desired logic is to implement __iter__.

If you don't overload __contains__ python would use __iter__ (if it's overloaded) to check whether or not your data structure contains specified value.

jedzer
  • 56
  • 2