Python中布尔表达式的求值 [英] Evaluation of boolean expressions in Python

查看:24
本文介绍了Python中布尔表达式的求值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What truth value do objects evaluate to in 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.

这篇关于Python中布尔表达式的求值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆