我正在练习exec()中的函数定义,但是在调用这个函数的时候,一些奇怪的行为把我搞糊涂了,请多多指教!
在实践中-1,即使我可以在本地变量()中找到'exec_func‘对象,但在调用函数时仍然得到错误'NameError: name 'exec_func’is not defined‘。在Practice-2和Practice-3中,该函数可以完美地执行。
### Practice-1 ###
# Define exec_func in function body, and invoked directly
def main_func():
x = 5
exec('''def exec_func(p1, p2):
return p1 + p2''')
print('locals = ', locals())
print('exec_func=', exec_func(x, 3))
if __name__ == '__main__':
main_func()
### Practice-2 ###
# Define exec_func in function body, and invoked through locals()
def main_func():
x = 5
func = None
exec('''def exec_func(p1, p2):
return p1 + p2''')
print('locals = ', locals())
func = locals()['exec_func']
print('exec_func=', func(x, 3))
if __name__ == '__main__':
main_func()
### Practice-3 ###
# define exec_func out of function body, and invoked directly
x = 5
dic = None
exec('''def exec_func(p1, p2):
return p1 + p2''')
print('locals = ', locals())
print('exec_func=', exec_func(x, 3))所以,基本上让我困惑的是: 1.在实践中-1.为什么'exec_func‘不能直接调用,即使它是在局部变量()中调用的。2. Practice-3和Practice-1相似,只是一个在函数体中,一个在函数体之外,为什么Practice-3可以完美地执行。
发布于 2019-07-02 14:09:53
如果你像下面这样在globals中设置它,那么Practise-1代码将会工作。默认情况下,只在globals中查找任何符号(这里是您的函数)。
def main_func():
x = 5
exec('''def exec_func(p1, p2):
\treturn p1 + p2''')
print('locals = ', locals())
globals()['exec_func'] = locals()['exec_func']
print('exec_func=', exec_func(x, 3))
if __name__ == '__main__':
main_func()输出:
locals = {'x': 5, 'exec_func': <function exec_func at 0x10f695378>}
exec_func= 8以下是为当地人准备的文档
Help on built-in function locals in module builtins:
locals()
Return a dictionary containing the current scope's local variables.
NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.
(END)https://stackoverflow.com/questions/56846074
复制相似问题