Linux 拨号vps windows公众号手机端

python怎么动态生成函数

lewis 6年前 (2019-03-13) 阅读数 8 #程序编程
文章标签 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())

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门