使用python检查字典中是否存在键时的AttributeError

使用python检查字典中是否存在键时的AttributeError,python,attributeerror,Python,Attributeerror,我使用的是Python 2.7.2+,在尝试查看字典是否包含给定的字符串值(名为func)时,出现以下异常: Traceback (most recent call last): File "Translator.py", line 125, in <module> elif type == Parser.C_ARITHMETIC : parseFunc() File "Translator.py", line 95, in parseFunc if unar

我使用的是Python 2.7.2+,在尝试查看字典是否包含给定的字符串值(名为func)时,出现以下异常:

Traceback (most recent call last):
  File "Translator.py", line 125, in <module>
    elif type == Parser.C_ARITHMETIC : parseFunc()
  File "Translator.py", line 95, in parseFunc
    if unary.has_key(func) : 
AttributeError: 'function' object has no attribute 'has_key'
以下是引发异常的函数:

def parseFunc():
    func = parser.arg1 
    print func  
    output.write("//pop to var1" + endLine)
    pop(var1)
    if unary.has_key(func) : // LINE 95
        unary()
        return
    output.write("//pop to var2" + endLine)
    pop(var2)
    result = "//"+func + endLine
    result += "@" + var1 + endLine
    result += "D=M" + endLine
    result += "@" + var2 + endLine
    output.write(result)
    if binary.has_key(func) : 
        binary()
    else : relational()
此外,我还尝试将
if-unary.has_key(func)
更改为
if-func-in-unary
,但后来我得到了

Traceback (most recent call last):
  File "Translator.py", line 126, in <module>
    elif type == Parser.C_ARITHMETIC : parseFunc()
  File "Translator.py", line 95, in parseFunc
    if func in unary:
TypeError: argument of type 'function' is not iterable
回溯(最近一次呼叫最后一次):
文件“Translator.py”,第126行,在
elif type==Parser.C_算术:parseFunc()
parseFunc中第95行的文件“Translator.py”
如果一元函数:
TypeError:类型“function”的参数不可iterable
另外,我还使用了Python3.2


有什么想法吗?感谢在Python3中,
dict.has_key()
已经不存在了(而且它已经被弃用了很长一段时间)。在我的字典中使用
x

不过,你的问题不同。虽然您的定义显示
一元
应该是一个字典,但回溯显示它实际上是一个函数。因此,在您没有显示的代码中的某个地方,
一元
被重新定义


即使
unary
是一个字典,您也无法调用它。

从您的跟踪来看,您似乎用一个函数覆盖了unary的值(您是否有任何称为“unary”的函数?)。因此,您试图对一个显然没有此类方法的函数调用“has_key”方法。请注意变量名,如果在代码中变量x放在def x()之后,它将覆盖def x(),反之亦然。

即使python 2.7.2+模棱两可,我认为问题不在于答案的第一部分,尽管它是正确的。@luke14free:你读了原始文章的倒数第二行了吗?
Traceback (most recent call last):
  File "Translator.py", line 126, in <module>
    elif type == Parser.C_ARITHMETIC : parseFunc()
  File "Translator.py", line 95, in parseFunc
    if func in unary:
TypeError: argument of type 'function' is not iterable