Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么要使用exec在类方法中动态创建函数';不行?_Python_Python 3.x - Fatal编程技术网

Python 为什么要使用exec在类方法中动态创建函数';不行?

Python 为什么要使用exec在类方法中动态创建函数';不行?,python,python-3.x,Python,Python 3.x,我从这篇文章中了解到,exec可以动态创建函数 我想在实例方法中动态创建一个函数,然后使用该函数 但是下面的代码失败了,为什么 class A: def method_a(self, input_function_str: str): exec('''def hello(): print('123') ''') # hello() # call hello() here leads to NameE

我从这篇文章中了解到,
exec
可以动态创建函数

我想在实例方法中动态创建一个函数,然后使用该函数

但是下面的代码失败了,为什么

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\u function\u str
动态创建一个函数,然后在
method\u a
中的某个位置使用该函数,在其他函数中使用
exec
动态定义的函数不会保存到该函数
locals()
。如果您将其保存到
globals()
作用域中,代码将正常工作,但您也可以在函数作用域之外调用
hello()

def方法(输入函数:str=None):
exec(“”“def hello():print('123')“”),globals())
打印('范围内:')
你好()
方法a()
打印('超出范围:')
你好()

有关更多信息,请参见此答案:

exec()
可以从当前作用域中获取内容,但无法将内容添加到作用域中,因此
hello
函数随后将丢失。不管怎么说,我不建议你这么做,看起来很不安全。这个用例是什么?这能回答你的问题吗?请注意,如果没有沙箱和其他预防措施,这将打开一个巨大的安全漏洞,因为输入字符串可能包含恶意代码。另见: