python中"变量或0"是什么意思?

alw*_*btc 23 python variables

python中以下语句的含义是什么:

x = variable_1 or 0
Run Code Online (Sandbox Code Playgroud)

variable_1是一个对象.x上面有什么价值?那是什么类型的x

jam*_*lak 22

x将是0如果variable_1评估为假,否则它将是variable_1

>>> 'abc' or 0
'abc'
>>> '' or 0
0
>>> ['a', 'b', 'c'] or 0
['a', 'b', 'c']
>>> [] or 0
0
Run Code Online (Sandbox Code Playgroud)


slo*_*oth 21

如果variable_1 求值为False,则x设置为0,否则为variable_1

把它想象成

if variable_1:
  x = variable_1
else:
  x = 0
Run Code Online (Sandbox Code Playgroud)

  • 更正确:如果`variable_1`是'None`或`False`或`0`,如果`__len__`存在于该对象上并返回'0`,如果该对象上存在`non_zero`并返回'0 `或`错误'.希望我没有忘记一些事情. (7认同)
  • 对于"无"或"错误" - 不仅仅是假的. (5认同)
  • 它实际上是`__nonzero__` ;-)或者,在Python 3中,更容易拼写`__bool__`. (5认同)