Reputation: 5074
I know that there are a number of magic methods in python that affect the way an object behaves in certain situations (like defining __cmp__(self, other)
to change the way it works when compared with another instance of itself), but I was wondering, is there a way to alter the behavior of how the object is called in an 'in' operator?
if thing in custom_object:
call_the_object_in_a_customized_way()
Would there be any way of doing this?
Upvotes: 0
Views: 1203
Reputation: 28352
Define the function __contains__
for this. It's invoked when you use the in
operator.
Demo:
>>> class Test:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __contains__(self, item):
return item in (self.a, self.c)
>>> a = Test(1, 2, 3)
>>> 1 in a
True
>>> 3 in a
True
>>> 2 in a
False
Upvotes: 4
Reputation: 97691
__contains__
is the method you're looking for
From this page:
For user-defined classes which define the
__contains__()
method,x in y
is true if and only ify.__contains__(x)
is true.For user-defined classes which do not define
__contains__()
but do define__iter__()
,x in y
is true if some valuez
withx == z
is produced while iterating overy
. If an exception is raised during the iteration, it is as if in raised that exception.Lastly, the old-style iteration protocol is tried: if a class defines
__getitem__()
,x in y
is true if and only if there is a non-negative integer indexi
such thatx == y[i]
, and all lower integer indices do not raiseIndexError
exception. (If any other exception is raised, it is as if in raised that exception).
Upvotes: 8