【发布时间】:2021-05-19 09:43:28
【问题描述】:
我了解到exec 可以从这篇帖子Python: dynamically create function at runtime 动态创建函数。
我想在实例方法中动态创建一个函数,然后使用该函数。
但是下面的代码失败了,为什么?
class A:
def method_a(self, input_function_str: str):
exec('''def hello():
print('123')
''')
# hello() # call hello() here leads to NameError
b = A()
b.method_a()
# hello() # call hello() here also leads to NameError
我的目标是根据从外部传递的input_function_str 动态创建一个函数,然后在method_a 的某个位置使用该函数。
【问题讨论】:
-
exec()可以从当前作用域中获取东西,但不能将东西添加到作用域中,因此hello函数之后会丢失。无论如何,我不建议这样做,似乎很不安全。这有什么用例? -
请注意,如果没有沙盒和其他预防措施,这会打开一个巨大的安全漏洞,因为输入字符串可能包含恶意代码。 另请参阅:stackoverflow.com/questions/1832940/…
标签: python python-3.x