開始的時候,需要用以下函數來做一個判斷,根據返回的值來做一些后續判斷處理:
def is_success(param):
if not param:
return False
return True
def process():
ret = is_sucess('p')
if ret:
print 'success'
else:
print 'failed'
process()
后來改需求了,要把失敗時返回的結果更細化一些,以便調用的時候可以提示更多內容,而不是單純的提示錯誤,於是把上面的函數做了如下改動
def is_success(param):
if param == 0:
return 0
elif param == 1:
return 1
return True
def process():
ret = is_sucess('p')
if ret == 0:
print 'failed-0'
elif ret == 1:
print 'failed-1'
else:
print 'success'
process()
結果調用的時候,問題來了,期待打印的‘success'沒有出現,而是打印出了了‘failed-1',也就是返回的 True 和 1 是相等的了,事實是這樣嗎?為什么呢?
在 ipython 中執行了一下,發現還真是,如下
In [1]: True == 1
Out[1]: True
查看一下文檔,發現 bool 是 int 的子類,並且僅有 True 和 False 兩個實例,這也就解釋了為什么 True == 1 為真了。
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
既然 bool 是 int 的子類,True 和 Fasle 也就可以進行算術運算了,測試了一下,果然如此!
In [3]: True + 2
Out[3]: 3
In [4]: True + True
Out[4]: 2
In [5]: False * 3
Out[5]: 0
In [6]: 4 / False
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-6-f1cbcd91af4b> in <module>()
----> 1 4 / False
ZeroDivisionError: integer division or modulo by zero
其實 True 和 False 在 Python2 中是內建變量,既然是變量,也就可以和別的變量一樣進行賦值了,其實這挺坑的,好在 Python3 中改成了關鍵字
# python2
In [14]: import __builtin__
In [15]: dir(__builtin__)[41]
Out[15]: 'True'
In [16]: True=233
In [17]: True
Out[17]: 233
In [22]: import keyword
In [23]: keyword.iskeyword(True)
Out[23]: False
In [24]: keyword.iskeyword('True')
Out[24]: False
在 Python3 中,True 被改成關鍵字了,這樣就不能隨便賦值導致一些潛在問題了
>>> import keyword
>>> keyword.iskeyword('True')
True
>>> True=2
File "<stdin>", line 1
SyntaxError: can't assign to keyword