python - 对于每个原始类型,Python 将什么视为 True 或 False?

标签 python evaluation nonetype expression-evaluation

def toBeOrNotToBe(x, y):
    return x or y

print(toBeOrNotToBe(0,1))
print(toBeOrNotToBe([],[1,2,3]))
print(toBeOrNotToBe('','something'))
print(toBeOrNotToBe(None, lambda _: None))
1
[1, 2, 3]
something
<function <lambda> at 0x0000015A20538708>

在哪里可以找到 Python 认为每种类型的 True 或 False 的完整列表? 如何为我的类编写自己的方法?

最佳答案

Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false:

  • constants defined to be false: None and False.

  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)

  • empty sequences and collections: '', (), [], {}, set(), range(0)

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.)

More details can be found here

关于python - 对于每个原始类型,Python 将什么视为 True 或 False?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60167029/

相关文章:

python - MongoDB - 将带有数组的一条记录转换为新集合中的多条记录

c++ - 像计算机一样思考的策略

c++ - 检查 Char/Int

python - 为什么在输出中打印 'None'?

python - 类型错误 : 'NoneType' object is not iterable in Python

python - 如何使用两个不同的用户运行 selenium webdriver?

python - 检查一个字符串的字母在另一个字符串中是否按顺序排列

python - 在 virtualenv 中安装 PyGtk

c - x<<y>>z C 中的求值顺序

Python:NoneType 对象没有属性 __getitem__。但它不是非类型