在字符串上使用exec定义函数中的函数

问题描述 投票:1回答:1
def square(n):
    def func(): pass
    s = 'def func(x): return x**2'
    exec(s)
    return func(n)

print(square(2))

在此代码中,exec(s)行未运行,因此未定义函子:TypeError:func()接受0个位置参数,但给出了1个那是因为虚拟函数正在运行并且不会被覆盖但是如果我跑

def square(n):
    def func(): pass
    def func(x): return x**2
    return func(n)

print(square(2))

正确输出

如果我再跑,则进一步:

def func(): pass
s = 'def func(x): return x**2'
exec(s)
print(func(2))

我得到正确的输出,因此可以使用'exec'定义函数

关于如何解决第一个错误并使用'exec'在函数内定义函数的任何评论

python python-3.x function
1个回答
0
投票

Using a function defined in an exec'ed string in Python 3

这帮了我很多,我花了一段时间才找到它

© www.soinside.com 2019 - 2024. All rights reserved.