在运行时定义Python函数
在Python中,我们可以在FunctionType()的帮助下定义一个在运行时执行的Python函数。首先我们导入types模块,然后执行compile()函数并传递参数 exec ,然后在 FunctionType() 的帮助下在运行时定义函数。
示例 1:打印 GEEKSFORGEEKS 的函数。
Python3
# importing the module
from types import FunctionType
# functttion during run-time
f_code = compile('def gfg(): return "GEEKSFORGEEKS"', "", "exec")
f_func = FunctionType(f_code.co_consts[0], globals(), "gfg")
# calling the function
print(f_func())
Python3
# importing the module
from types import FunctionType
# function at run-time
f_code = compile('def gfg(a, b): return(a + b) ', "", "exec")
f_func = FunctionType(f_code.co_consts[0], globals(), "gfg")
val1 = 3999
val2 =4999
# calliong the function
print(f_func(val1, val2))
输出:
GEEKSFORGEEKS
示例 2:添加 2 个数字的函数。
Python3
# importing the module
from types import FunctionType
# function at run-time
f_code = compile('def gfg(a, b): return(a + b) ', "", "exec")
f_func = FunctionType(f_code.co_consts[0], globals(), "gfg")
val1 = 3999
val2 =4999
# calliong the function
print(f_func(val1, val2))
输出:
8998