我意识到__contains__
是“in”运算符。我还意识到,默认情况下“不在”是 __contains__
的否定。 。然而,很多 python 文档都列出了“not in”,就好像它是与“in”不同的运算符。是__contains__
喜欢 __eq__
和__ne__
其中有两个运算符,一个通常是另一个的否定?如果是这样,正确的双下划线 __<name>__
是什么?使用?
def __init__(self):
self.numbers = [1,2,3,4,54]
def __contains__(self, key):
return key in self.numbers
最佳答案
没有单独的“notcontains” Hook 。 in
和 not in
不能单独覆盖。
存在单独的 __eq__
和 __ne__
Hook ,因为 ==
和 !=
可能不会返回 bool 值。例如,您不能将 NumPy 数组的 !=
实现为 not (x == y)
。 not in
不存在这个问题,因为 in
和 not in
都必须返回 bool 值。
如果你看data model documentation ,您会看到它只记录了 in
和 not in
的单个 __contains__
钩子(Hook)。您还可以查看implementation ,其中 in
和 not in
都调用相同的 PySequence_Contains
C API 函数,然后 not in
应用 !
结果:
case PyCmp_IN:
res = PySequence_Contains(w, v);
if (res < 0)
return NULL;
break;
case PyCmp_NOT_IN:
res = PySequence_Contains(w, v);
if (res < 0)
return NULL;
res = !res;
break;
关于python - 如何覆盖 python 的 "not in"运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58675851/