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, 0L, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
instances of user-defined classes, if the class defines a
__nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1]
> All other values are considered true — so objects of many types are
always true.
Operations and built-in functions that have a Boolean result always
return 0 or False for false and 1 or True for true, unless otherwise
stated. (Important exception: the Boolean operations or and and always
return one of their operands.)
所有对象(包括类型,它们是
type
的实例)本质上都是真的,因为它们表示存在基础类型的值,而None
表示不存在任何类型的值。(仅仅因为None
是NoneType
的一个实例,所以None
的计算结果为true是没有用的。)某些类型的某些实例(空字符串和容器类型的空实例,仅举几例)的计算结果改为
False
,因为这样考虑比较方便。你知道吗在您自己的类中,您可以重写特定实例的真值,方法是重写^{} 或
__len__
,为特定实例返回0或False
。你知道吗来自文档:
因为所有类型都是从object派生的,
__nonzero__
不返回False或integer zero,并且它们没有__len__
方法,所以它被认为是True。你知道吗还有一件有趣的事: ^float的{}是
<slot wrapper '__nonzero__' of 'float' objects>
以下是一些信息: What is a wrapper_descriptor, and why is Foo.__init__() one in this case?
基本问题是:
这个规则是用来定义Python(should)如何操作的:只要有一个if语句的值不是
True
或False
,结果就应该很清楚。所有实现都一样!你知道吗这并不意味着它是一种好的风格。也不应该用它
我个人不知道会印什么。我不会查的,反正是不好的。我总是告诉我的学生:“即使编译器理解了,你们学校也不会”
相关问题 更多 >
编程相关推荐