Python中has_key的錯誤調試分析

來源:互聯網
上載者:User

今晚像往常一樣開啟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版本:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.