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
本文详细解析Python内建类型中的真值检测机制,包括如何通过if或while条件进行判断,以及如何在布尔运算中使用这些值。重点讨论了False、None、零值、空序列、空映射等被视为假值的对象,并解释了自定义类实例在特定方法存在的情况下如何被评估。同时,阐述了所有非空值均为真值的基本原则。
954

被折叠的 条评论
为什么被折叠?



