Python的bool类型
寫習慣了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'的就是:
不知道是否有更好的方法呢?
轉載于:https://www.cnblogs.com/QLeelulu/archive/2009/09/20/1570292.html
總結
以上是生活随笔為你收集整理的Python的bool类型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2021-07-27-jeesite学习
- 下一篇: python-k近邻分类器-KNN