我知道python中有许多神奇的方法会影响对象在某些情况下的行为方式(例如定义__cmp__(self, other)
以更改其与自身另一个实例相比的工作方式),但我想知道,有没有办法改变对象在"in"运算符中调用方式的行为?
if thing in custom_object:
call_the_object_in_a_customized_way()
有什么办法可以做到这一点吗?
__contains__
是您要查找的方法
从此页面:
对于定义
__contains__()
方法的用户定义类,当且仅当y.__contains__(x)
为 true 时,x in y
为 true。对于不定义
__contains__()
但 定义__iter__()
,x in y
如果某个值与x == z
z
为 真 在迭代y
时产生。如果在 迭代,就好像在提出那个例外。最后,尝试旧式迭代协议:如果一个类定义
__getitem__()
,x in y
为真当且仅当存在一个非负整数索引i
使得x == y[i]
,并且所有较低的整数索引都 不提出IndexError
例外。(如果提出任何其他例外,则 好像在提出那个例外)。
为此定义函数__contains__
。使用 in
运算符时将调用它。
演示:
>>> 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