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
orwhile
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
orFalse
for false and1
orTrue
for true, unless otherwise stated. (Important exception: the Boolean operationsor
andand
always return one of their operands.)
关于python - 对于每个原始类型,Python 将什么视为 True 或 False?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60167029/