Python中布尔表达式的求值

2022-01-19 00:00:00 python object boolean

问题描述

对象在 Python 中求值的真值是多少?

What truth value do objects evaluate to in Python?

相关问题

  • Python 中对象的布尔值:关于重写方式的讨论被评估
  • Boolean Value of Objects in Python: Discussion about overriding the way it is evaluated

解决方案

任何事物都可以被检验为真值,用于 if 或 while条件或作为布尔值的操作数下面的操作.以下值被认为是错误的:

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:

错误

任何数字类型的零,例如,00L0.00j.

zero of any numeric type, for example, 0, 0L, 0.0, 0j.

任何空序列,例如,''()[].

any empty sequence, for example, '', (), [].

任何空映射,例如,{}.

用户定义类的实例,如果该类定义了 __nonzero__()__len__() 方法,当该方法返回整数零或 bool值 False.

instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.

所有其他值都被认为是真的——所以许多类型的对象总是真实的.除非另有说明,否则具有布尔结果的操作和内置函数始终返回 0 或 False 表示 false 和 1 或 True 表示 true.(重要的例外:布尔运算或"和和"总是返回它们的操作数之一.)

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 return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations "or" and "and" always return one of their operands.)

https://docs.python.org/2/库/stdtypes.html#truth-value-testing

如前所述,您可以通过修改非零值来覆盖自定义对象.

And as mentioned, you can override with custom objects by modifying nonzero.

相关文章