2

我正在使用 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'

这是我定义字典的地方:

binary = {"add":'+', "sub":'-', "and":'&', "or":'|'}
relational = {"eq":"JEQ" , "lt":"JLT", "gt":"JGT"}
unary = {"neg":'-'}

这是引发异常的函数:

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

PS我也用python 3.2厌倦了它

有任何想法吗?谢谢

4

2 回答 2

5

在 Python 3 中,dict.has_key()它已经消失了(并且已经被弃用了很长一段时间)。改为使用x in my_dict

不过,您的问题是另一回事。虽然您的定义显示unary应该是字典,但回溯显示它实际上是一个函数。因此,您未显示的代码中的某处unary被重新定义。

即使unary是字典,你也无法调用它。

于 2012-04-13T19:09:25.110 回答
1

从您的跟踪来看,您似乎用函数覆盖了一元的值(您有任何称为“一元”的函数吗?)。因此,您试图在显然没有这种方法的函数上调用“has_key”方法。注意变量名,如果变量 x 放在代码中,它会覆盖 def x(),反之亦然。

于 2012-04-13T19:16:40.487 回答