exec我想像这样定义一个Python函数:
exec """def my_func(alpha = 'a'):
return alpha"""
Run Code Online (Sandbox Code Playgroud)
有用。alpha = 'a'但是,出于特定原因,我想在单独的字符串中定义:
s = "alpha = 'a'"
exec """def my_func(s):
return alpha"""
Run Code Online (Sandbox Code Playgroud)
但这不起作用。有没有办法以这种方式将字符串变量内容插入到多行注释字符串中?
使用格式化函数:
s = "alpha = 'a'"
exec """def my_func({}):
return alpha""".format(s)
Run Code Online (Sandbox Code Playgroud)