我找不到与not x
运算符对应的方法。不过,and、or 和 xor 有一个。它在哪里?
最佳答案
and
或 or
运算符没有钩子(Hook),没有(因为它们短路),并且没有 xor
运算符Python。 __and__
和 __or__
用于 bitwise &
and |
operators , 分别。 not
的等效位运算符是 ~
(反转),它由 __invert__
method 处理, 而 __xor__
涵盖了 ^
按位运算符。
not
在 truth-value of an object 上运行.如果你有一个容器,给它一个 __len__
method , 如果不给它 __bool__
method .咨询其中任何一个以确定一个对象是否应该被认为是“真实的”; not
反转该测试的结果。
因此,如果 __bool__
返回 True
或 __len__
返回 0
以外的整数,不
会将其反转为 False
,否则 not
会生成 True
。请注意,您不能让 not
返回除 bool 值以外的任何其他内容!
来自 __bool__
的文档:
__bool__
Called to implement truth value testing and the built-in operationbool()
; should returnFalse
orTrue
. When this method is not defined,__len__()
is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither__len__()
nor__bool__()
, all its instances are considered true.>
对于 not
expression :
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false:
False
,None
, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a__bool__()
method.The operator
not
yieldsTrue
if its argument is false,False
otherwise.
大胆强调我的。
关于python - 在 Python 中覆盖 'not' 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39754808/