今晚像往常一樣開啟Aptana寫Python程式時,一個has_key調用報錯了,代碼如下:
| 代碼如下 |
複製代碼 |
info = {} info.has_key("key") 控制台: Traceback (most recent call last): File "D:\workspace\aptana\test\main.py", line 8, in <module> print(info.has_key("email")) www.111cn.net AttributeError: 'dict' object has no attribute 'has_key' |
說是字典對象沒有has_key這個屬性?一開始我以為是電腦神經了,多運行幾次,還是報這個錯誤。看來電腦是沒問題,在仔細讀程式,一點問題都沒有啊!後來想到會不會因為info沒有成員才會報錯?這不可能,但我還是往info裡加了成員:
| 代碼如下 |
複製代碼 |
info = {"key":"key"} print(info.has_key("key")) )
|
結果還是一樣提示字典對象沒有has_key這個屬性,於是我拿到命令列下運行,居然跑通了?
| 代碼如下 |
複製代碼 |
D:\Python27>python.exe D:\workspace\aptana\test\main.py True
|
正嚴重鬱悶中,難道Aptana中的PyDev出毛病了?但其他的語句比如if..else..while...def...class..import等都沒有問題,為何偏偏就不能用has_key?最後我決定把Python的版本列印看看:
| 代碼如下 |
複製代碼 |
import sys print(sys.version) |
控制台:
| 代碼如下 |
複製代碼 |
3.3.4 (v3.3.4:7ff62415e426, Feb 10 2014, 18:13:51) [MSC v.1600 64 bit (AMD64)]
|
Python3版本,到cmd下列印Python版本:
| 代碼如下 |
複製代碼 |
D:\Python27>python.exe -V Python 2.7.5 |
Python2版本,難道說Python3版本移除了has_key這個我最經常用的函數?到官網一查,發現如下這段話:
Removed: apply(). Instead of apply(f, args) use f(*args).
Removed callable(). Instead of callable(f) you can use isinstance(f, collections.Callable). The operator.isCallable() function is also gone.
Removed coerce(). This function no longer serves a purpose now that classic classes are gone.
Removed execfile(). Instead of execfile(fn) use exec(open(fn).read()).
Removed the file type. Use open(). There are now several different kinds of streams that open can return in the io module.
Removed reduce(). Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable.
Removed reload(). Use imp.reload().
Removed. dict.has_key() – use the in operator instead.
這真是中招了,還好沒有浪費太多時間,沒有把編輯器、系統重裝,最後查看項目建立時使用的解譯器果真是Python3版本: