class ExecUtil: tmpMap = {} @classmethod def exec_code(cls, function_str, call_str, param_dict): """ 动态执行函数,必须按照示例的函数传入,设计到提取函数方法和参数 :param function_str: 函数代码 :param call_str: :param param_dict: 入参 :return: """ result = {} tmp_key = "tmp_result_625d7c4c3daa411f9cf8b14441e65539" function_str += f"\n{tmp_key}['res']={call_str}" if function_str in cls.tmpMap: cmp_code = cls.tmpMap[function_str] else: cmp_code = compile(function_str, '', 'exec') cls.tmpMap[function_str] = cmp_code exec(cmp_code, {}, {**param_dict, tmp_key: result}) return result['res'] # cmd_str = """ # def factorial(num): # fact=1 # for i in range(1,num+1): # fact = fact*i # return fact # """ # # start = time.time() # for x in range(10000): # ExecUtil.exec_code(cmd_str, 'factorial(num)', {"num": 3}) # print(time.time() - start) class User: def __init__(self): self.dic = {} self.a = 0 def test1(self, b): print(ExecUtil.exec_code(""" def test2(self, b): import time print(time.time()) self.dic['c'] = b+1 self.a = b return b+2 """, "test2(self, b)", {"self": self, "b": b})) user = User() user.test1(3) print(user.dic)