Python的bool类型
2009-09-20 00:48
232 查看
写习惯了C#的代码,在想要将一个字符串'False'转换为bool型的时候,很自然的写了如下的Python代码:
看到上面的结果了没?是True。突然记起Python中除了''、""、0、()、[]、{}、None为False之外,其他的都是True。也就是说上面的'False'就是一个不为空的字符串,所以结果就为True了。
为了深入了解下Python的bool类型,就看了下说明:
>>> help(True)
Help on bool object: 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|y 可以看到bool是int的子类来的,并且不可以子类化:
因为bool为int的子类,所以用1表示True,0表示False:
看到上面2==True是为false的。但是我们看下面的代码:
我们看到True被打印出来了,我想这样是因为if语句会在内部去调用bool()方法:
因为bool是继承自int类型的,所以我猜想在比较的时候最终是会转换为0和1来比较的,就像:
(注:这里只是猜想,未经证实)
既然bool是继承自int类型的所以很自然bool类型是支持数学运算的:
最后,我能想到的判断字符串是否有'False'的就是:
不知道是否有更好的方法呢?
看到上面的结果了没?是True。突然记起Python中除了''、""、0、()、[]、{}、None为False之外,其他的都是True。也就是说上面的'False'就是一个不为空的字符串,所以结果就为True了。
为了深入了解下Python的bool类型,就看了下说明:
>>> help(True)
Help on bool object: 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|y 可以看到bool是int的子类来的,并且不可以子类化:
因为bool为int的子类,所以用1表示True,0表示False:
看到上面2==True是为false的。但是我们看下面的代码:
我们看到True被打印出来了,我想这样是因为if语句会在内部去调用bool()方法:
因为bool是继承自int类型的,所以我猜想在比较的时候最终是会转换为0和1来比较的,就像:
(注:这里只是猜想,未经证实)
既然bool是继承自int类型的所以很自然bool类型是支持数学运算的:
最后,我能想到的判断字符串是否有'False'的就是:
不知道是否有更好的方法呢?
相关文章推荐
- python - 基础类型 - bool
- python基础篇之bool类型
- Python 基础 - 4 常用数值类型(int,float,bool)操作
- Python基础:数值类型、常用函数、工具模块以及bool类型本质
- Python 文件处理 Bool类型
- Python-bool 类型
- 【Python 第18课】 bool类型转换
- python基础教程共60课-第18课bool类型转换
- Python-bool 类型
- Python 基础 - 3 常用数值类型(int,float,bool)定义
- python 中的True和1及False和0是可以等价比较及是否是bool类型
- Python3基础 bool类型变量赋值
- Python Numpy data-type dtype 自定义数据类型
- python里如何保存float类型的小数的位数
- Python中判断输入数据的类型
- 第三章 Python丰富的数据类型
- c# 调用c++ dll文件中的bool类型解决办法
- Python 异常类型
- go布尔bool类型
- python2.7学习笔记(二)List和Tuple类型