Override Python's 'in' operator?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Track title: CC M Beethoven - Piano Sonata No 3 in C 3
--
Chapters
00:00 Question
00:24 Accepted answer (Score 332)
00:38 Answer 2 (Score 269)
01:10 Answer 3 (Score 2)
01:36 Thank you
--
Full question
https://stackoverflow.com/questions/2217...
Accepted answer links:
[MyClass.__contains__(self, item)]: http://docs.python.org/reference/datamod...
Answer 2 links:
[documentation on overloading ]: http://docs.python.org/reference/datamod...
Answer 3 links:
[__iter__]: https://docs.python.org/3/reference/data...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #operatoroverloading #operators #inoperator
#avk47
--
Track title: CC M Beethoven - Piano Sonata No 3 in C 3
--
Chapters
00:00 Question
00:24 Accepted answer (Score 332)
00:38 Answer 2 (Score 269)
01:10 Answer 3 (Score 2)
01:36 Thank you
--
Full question
https://stackoverflow.com/questions/2217...
Accepted answer links:
[MyClass.__contains__(self, item)]: http://docs.python.org/reference/datamod...
Answer 2 links:
[documentation on overloading ]: http://docs.python.org/reference/datamod...
Answer 3 links:
[__iter__]: https://docs.python.org/3/reference/data...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #operatoroverloading #operators #inoperator
#avk47
ACCEPTED ANSWER
Score 359
ANSWER 2
Score 280
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
ANSWER 3
Score 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.