class all_items(dict):
def __getitem__(self, key):
return 1
>>> eval("undefined",dict(),all_items())
1
>>> eval("undefined",all_items(),dict())
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
eval("undefined",all_items(),dict())
File "<string>", line 1, in <module>
NameError: name 'undefined' is not defined
字典的 all_items 类对于任何值都应该返回 1。使用 eval 函数,我希望“未定义”的计算结果为 1,即使它尚未定义。当 all_items 字典是 eval 语句的第三个参数时,这有效,但当它是第二个参数时,则无效。我的问题是为什么第二个语句的计算结果不为 1? (我怎样才能让它工作?)我使用的是 Python 2.5。
最佳答案
第二个参数 must be a dictionary 。实现映射协议(protocol)还不够。
关于python - eval 函数的第二个参数与第三个参数有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4048830/