函数中的评估范围
Eval scope in a function
我有以下脚本从字符串列表创建字典:
def dummy(a, b):
c = a+1
lst =["a","b","c"]
return dict((k, eval(k)) for k in lst)
if __name__ == "__main__":
dummy(0.01, "2015-01-29")
当我在终端中 运行 时,出现以下错误:
NameError: name 'a' is not defined
当eval
起作用时,似乎在函数dummy
的范围内找不到变量a
...但我不明白为什么...
先列一个清单:
def dummy(a, b):
c = a + 1
lst =["a","b","c"]
return dict([(k, eval(k)) for k in lst])
if __name__ == "__main__":
print(dummy(0.01, "2015-01-29"))
您的版本是生成器。有关详细信息,请参阅此内容:
- scope of eval function in python
引用相关部分:
The scope of names defined in a class block is limited to the class
block; it does not extend to the code blocks of methods – this
includes generator expressions since they are implemented using a
function scope.
我有以下脚本从字符串列表创建字典:
def dummy(a, b):
c = a+1
lst =["a","b","c"]
return dict((k, eval(k)) for k in lst)
if __name__ == "__main__":
dummy(0.01, "2015-01-29")
当我在终端中 运行 时,出现以下错误:
NameError: name 'a' is not defined
当eval
起作用时,似乎在函数dummy
的范围内找不到变量a
...但我不明白为什么...
先列一个清单:
def dummy(a, b):
c = a + 1
lst =["a","b","c"]
return dict([(k, eval(k)) for k in lst])
if __name__ == "__main__":
print(dummy(0.01, "2015-01-29"))
您的版本是生成器。有关详细信息,请参阅此内容:
- scope of eval function in python
引用相关部分:
The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes generator expressions since they are implemented using a function scope.