Override Python's 'in' operator?
Question:
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:
...
Answers:
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
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.
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:
...
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
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.