__bool__
Called to implement truth value testing and the built-in operation bool(); should return False or True. 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.>
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 yields True if its argument is false, False otherwise.
您看到的方法是针对位},而不是}(这甚至不是Python运算符)。在
&
,|
,和{and
,or
,或{not
不能重载,就像and
和{~
可以重载;这是__invert__
。在如果您希望能够重载
not
,那么您要么只能使用重载~
,要么必须编写自己的logical_not
函数,并使用它来代替not
运算符。在在Python中没有}分别用于bitwise ^{} and ^{} operators 。} method 处理,而^{} 覆盖了{}位运算符。在
and
或or
运算符的钩子,没有(因为它们短路),而且Python中也没有xor
运算符。__and__
和{not
的等价位运算符是~
(反转),它由^{not
操作truth-value of an object。如果你有一个容器,给它一个^{not
反转该测试的结果。在因此,如果}生成{}。请注意,您不能使
__bool__
返回True
或__len__
返回0
以外的整数,not
会将其转换为False
,否则{not
只返回布尔值!在来自
__bool__
的文档:对于^{} expression :
bold emphasis我的。在
相关问题 更多 >
编程相关推荐