写习惯了C#的代码,在想要将一个字符串'False'转换为bool型的时候,很天然的写了以下的Python代码:web
看到上面的结果了没?是True。忽然记起Python中除了''、""、0、()、[]、{}、None为False以外,其余的都是True。也就是说上面的'False'就是一个不为空的字符串,因此结果就为True了。ui
为了深刻了解下Python的bool类型,就看了下说明:spa
>>> help(True)
Help on bool object:orm
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
|
| Methods defined here:
|
| __and__(...)
| x.__and__(y) <==> x&y
|
| __or__(...)
| x.__or__(y) <==> x|yblog
能够看到bool是int的子类来的,而且不能够子类化:继承
由于bool为int的子类,因此用1表示True,0表示False:字符串
看到上面2==True是为false的。可是咱们看下面的代码:get
咱们看到True被打印出来了,我想这样是由于if语句会在内部去调用bool()方法:数学
由于bool是继承自int类型的,因此我猜测在比较的时候最终是会转换为0和1来比较的,就像:it
(注:这里只是猜测,未经证明)
既然bool是继承自int类型的因此很天然bool类型是支持数学运算的:
最后,我能想到的判断字符串是否有'False'的就是:
不知道是否有更好的方法呢?