我已经看到以下情况:
>>> def func(a): ... if a: ... print("True") ... >>> a = [1, 2, 3] >>> func(a) True >>> a == True False为什么会出现这种差异?
Why does this difference occur?
推荐答案Python中的所有对象 1 都具有真实值:
All objects1 in Python have a truth value:
可以测试任何对象的真值,以用于if或while条件,或用作以下布尔运算的操作数.以下值被认为是错误的:
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
任何数字类型的零,例如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.
1 …,除非它们具有引发异常的__bool__()方法,或者返回除True或False之外的其他值.前者是不寻常的,但有时是合理的行为(例如,请参见下面的user2357112的注释);后者不是.
1 … 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对象的正确和错误标准是什么?
发布评论