对于每种原始类型,Python认为True或False是什么? [重复]

问题描述 投票:1回答:1
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的完整列表?如何为自己的类编写自己的方法?

python evaluation nonetype expression-evaluation
1个回答
0
投票

真值测试

可以测试任何对象的真值,以供使用在ifwhile条件下或作为布尔运算的操作数下面。

默认情况下,除非对象的类定义返回False的__bool__()方法或__len__()方法与物件呼叫时传回零。这是大多数内置对象被认为是错误的:

  • 常量定义为假:无和为假。

  • 任何数字类型的零:0、0.0、0j,小数(0),小数(0、1)

  • 空序列和集合:'',(),[],{},set(),range(0)

总是具有布尔结果的操作和内置函数否则返回0False,否则返回1True,除非另有说明说。 (重要的例外:布尔运算orand始终返回其操作数之一。)

More details can be found here

© www.soinside.com 2019 - 2024. All rights reserved.