问题描述
我已经看到以下情况:
>>> def func(a):
... if a:
... print("True")
...
>>> a = [1, 2, 3]
>>> func(a)
True
>>> a == True
False
为什么会出现这种差异?
Why does this difference occur?
推荐答案
Python中的所有对象都具有真实值:
All objects in Python have a truth value:
-
None
False
任何数字类型的零,例如0
,0.0
,0j
.
zero of any numeric type, for example, 0
, 0.0
, 0j
.
任何空序列,例如''
,()
,[]
.
any empty sequence, for example, ''
, ()
, []
.
任何空映射,例如{}
.
实例,如果该类定义了__bool__()
或__len__()
方法,则当该方法返回整数零或布尔值False
时.
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
.
所有其他值都被视为true,因此许多类型的对象始终为true.
All other values are considered true — so objects of many types are always true.
…,除非它们具有引发异常的__bool__()
方法,或者返回除True
或False
之外的其他值.前者是不寻常的,但有时是合理的行为(例如,请参见下面的user2357112的注释);后者不是.
… unless they have a __bool__()
method which raises an exception, or returns a value other than True
or False
. The former is unusual, but sometimes reasonable behaviour (for example, see the comment by user2357112 below); the latter is not.
这篇关于python对象的正确和错误标准是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!