调用exec()中定义的函数的问题



我正在练习exec((中练习函数定义,但是当调用函数时,一些怪异的行为使我感到困惑,请需要您的帮助!

在练习1中,即使我可以在locals((中找到'exec_func'对象,但是在调用函数时仍未定义错误'nameError:name'exec_func'。在练习2和实践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.练习-3类似于练习1,差异仅在于,一个在功能主体中,另一个是不合时宜的,为什么练习3执行完美。

好吧,如果您将其设置在globals中,则实践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)

最新更新