Python内建类型之真值检测(Truth Value Testing)
Manual
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
-
None
-
False
-
zero of any numeric type, for example,0, 0.0, 0j.
-
any empty sequence, for example, '',(), [].
-
any empty mapping, for example, {}.
-
instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero orbool valueFalse.
All other values are considered true — so objects of many types are always true.
Operations and built-in functions that have a Boolean result always return0 orFalse for false and1 orTrue for true, unless otherwise stated. (Important exception: the Boolean operationsor andand always return one of their operands.)
直译
任意对象可以通过‘使用 if 或 while条件’或‘在布尔预算中作为操作数’来检测真值。以下值被认为是否:
- None
- False
- 任意数值类型的0值,例如:0, 0.0, 0j
- 任意空序列,例如:‘’,[],()
- 任意空映射,例如:{}
- 自定义类的实例,如果类定义了__bool__()或__len__()方法,当方法返回整数0或布尔值False