python怎么动态生成函数

1361
2021/3/5 13:57:47
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

python怎么动态生成函数

在python中使用types.FunctionType方法动态生成函数,具体方法如下:

from types import FunctionType, CodeType

code_1 = """

def uuid()->str:

import uuid

return str(uuid.uuid1())"""

foo_compile = compile(code_1 , "", "exec")

foo_code = [ i for i in foo_compile.co_consts if isinstance(i, CodeType)][0]

globals()['uuid'] = FunctionType(foo_code, globals())

func = globals()['uuid']

print(func())

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: python切片负数如何看