我想创建一个可以在in
条语句中使用的类,并将条件传递给__init__
中的对象.例如:
class Set:
def __init__(self, contains):
self.__contains__ = contains # or setattr; doesn't matter
top = Set(lambda _: True)
bottom = Set(lambda _: False)
问题是3 in top
返回TypeError: argument of type 'Set' is not iterable
,尽管top.__contains__(3)
按预期返回True
.
此外,如果我修改代码如下:
class Set:
def __init__(self, contains):
self.__contains__ = contains
def __contains__(self, x):
return False
top = Set(lambda _: True)
,3 in top
将返回False
,而top.__contains__(3)
将再次按预期返回True
.
这里发生了什么?我使用的是Python 3.9.2.
(注意:属于data model的其他方法也会发生同样的情况,例如__gt__
、__eq__
等)