Python中的bool
2017-07-20 18:02:52 +08 字数:1277 标签: Pythonbool类型 ¶
Python也受到了C语言的深刻影响,最初也是用int来做逻辑判断的。 好在Python 2.2版本以后,加入了bool类型。
Python 2.3版本,加入了True与False。
类型bool是继承于int的,所以True和False也可以当成1和0。
>>> False == 0
True
>>> True + 1
2
当然,这是历史遗留问题,不建议这样去使用。
从Python 3开始,True与False都成为关键字。
是关键字,意味着不能被篡改。
>>> True = 1
SyntaxError: can't assign to keyword
在Python 2中,True与False只是内置常量,可以随意赋值。
bool() ¶
首先,bool()不是一个普通函数,而是一个类的构造操作。
通过pydoc bool,可以看到文档。
Help on class bool in module __builtin__:
class bool(int)
| bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.
|
| Method resolution order:
| bool
| int
| object
这是一个『二例模式』。 与单例模式类似,只是有且仅有两个实例。
它会把一些其它类型的东西,转换成bool类型的True或False。
在很多需要逻辑判断的地方,都会做默认的转换。
比如,if a:,就等价于if bool(a):。
取反(not) ¶
not是一个关键字。
有些类似于C语言家族的!,它可以实现逻辑取反操作。
not后面可以放任何类型。
not a,可以等价看做not bool(a)。
需要注意的是,not和is not,是完全不同的。
is not可以看做是一个组合关键字,是对不等的判断。
a is not b,基本等价于not (a is b),只是可读性更高。
>>> not None
True
>>> False is not None
True
>>> False is (not None)
False
>>> not (False is None)
True
_bool_() ¶
关于Python中的bool,最深的一层大概就是这里了。
多数人认为,除了基本类型里的False、None、0、()、[]、{}、''以外,
对其它的东西使用bool(),结果都是True。
这是典型的误解。
『基本类型』一说,本就有些不妥。 像C语言,会区分基本类型与结构体; 像Java,会区分基本类型与类。 那是因为,C语言需要操作硬件,而Java也需要考虑到性能因素。
对Python来说,一切皆对象。
理解到这一层,就会发现,0、''、[]这些东西,不过也是对象而已。
那么,为什么它们的bool(),返回结果不同?
在object.__bool__的文档中,可以得到答案。
object.__bool__(self)
Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true.
只要一个类实现了__bool__()这个Method,那么它的实例的bool()结果,就是这个方法的返回值。
而如果一个类没有__bool__(),那么就会判断其__len__()的返回值是否为0。
如果都没有,则全部返回True。
这就是[]这些东西会被转换为False的原因。
同样,通过实现这个Method,俺们也可以定制自己的class,
令其在bool()或not情况下,有不同的表现。
>>> class a:
>>> def __bool__(self):
>>> return False
>>> bool(a())
False
>>> not a()
True
Python 2里的__bool__ ¶
Python 2中没有__bool__(),而是用的__nonzero__()。
其余内容都相同,详见object._nonzero_文档。