今晚像往常一样打开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"))
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)
Console Output:
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版本:
没办法,还是老实的使用key in dict
吧!