python 对象的真假标准是什么?

What are the true and false criteria for a python object?

我见过以下案例:

>>> def func(a):
...     if a:
...         print("True")
...
>>> a = [1, 2, 3]
>>> func(a)
True
>>> a == True
False

为什么会出现这种差异?

当您键入 if a: 时,它等同于 if bool(a):。所以这并不意味着 a is True,只是 a 作为布尔值的表示是 True.

一般来说boolint的子类,其中True == 1False == 0.

Python 中的所有对象1 都有一个 truth value:

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:

  • None

  • False

  • zero of any numeric type, for example, 0, 0.0, 0j.

  • any empty sequence, for example, '', (), [].

  • any empty mapping, for example, {}.

  • instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False.

All other values are considered true — so objects of many types are always true.


1 …除非他们有一个引发异常的 __bool__() 方法,或者 returns 除了 TrueFalse。前者是不寻常的,但有时是合理的行为(例如,参见下面 user2357112 的评论);后者不是。