[英]AttributeError when checking if a key exist in a dictionary, using python
I am using Python 2.7.2+, and when trying to see if a dictionary holds a given string value (named func) I get this exception: 我正在使用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'
This is where I define the dictionaries: 这是我定义字典的地方:
binary = {"add":'+', "sub":'-', "and":'&', "or":'|'}
relational = {"eq":"JEQ" , "lt":"JLT", "gt":"JGT"}
unary = {"neg":'-'}
Here's the function where the exception is raised: 这是引发异常的函数:
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()
Also, I tried changing if unary.has_key(func)
to if func in unary
but then I got 另外,我尝试将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 I tired it also using python 3.2 PS我也用python 3.2累了
Any ideas? 有任何想法吗? Thanks 谢谢
In Python 3, dict.has_key()
is gone (and it has been deprecated for quite some time). 在Python 3中, dict.has_key()
消失了(并且已弃用了相当长的一段时间)。 Use x in my_dict
instead. x in my_dict
使用x in my_dict
代替。
Your problem is a different one, though. 但是,您的问题是另一个问题。 While your definition shows unary
should be a dictionary, the traceback shows it actually is a function. 虽然您的定义显示unary
应该是一个字典,但是回溯显示它实际上是一个函数。 So somewhere in the code you did not show, unary
is redefined. 因此,在您未显示的代码中的某处, unary
被重新定义。
And even if unary
was a dictionary, you would not be able to call it. 即使unary
字典是一本字典,您也无法调用它。
It seems from your trace that you override the value of unary with a function (do you have any function called "unary"?). 从您的跟踪中看来,您使用一个函数覆盖了一元的值(您是否有任何称为“一元”的函数?)。 Therefore you are trying to call "has_key" method on a function that obviously has no such method. 因此,您试图在显然没有此类方法的函数上调用“ has_key”方法。 Pay attention with variable names, variable x will override def x() if it's placed after it in your code, and vice versa. 请注意变量名,如果变量x放置在代码中,则变量x将覆盖def x(),反之亦然。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.