views:

341

answers:

3

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:
    ...
+18  A: 

MyClass.__contains__()

Ignacio Vazquez-Abrams
This is the correct answer!
Noctis Skytower
+6  A: 

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
pthulin
@pthulin, yours may be "more complete" in terms of code, but Ignacio's links to the documentation, which is always a big plus for some.
Peter Hansen
A: 

You might also want to take a look at an infix operator override framework I was able to use to create a domain-specific language:

http://code.activestate.com/recipes/384122/