Search code examples
pythonoperator-overloadingoperatorsin-operator

Override Python's 'in' operator?


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:
    ...

See also What does __contains__ do, what can call __contains__ function for the corresponding question about what __contains__ does.


Solution

  • MyClass.__contains__(self, item)