简体   繁体   English

如何在 python 中动态创建函数

[英]How to dynamically create functions in python

I am trying to make an interpreter of code written in some language in python and currently stuck on interpreting functions.我正在尝试对用 python 中的某种语言编写的代码进行解释器,目前停留在解释函数上。 It seems there is a way of creating classes dynamically with something like MyClass = type("MyClass", (object, ), dict()) but I can't find a way of creating functions.似乎有一种方法可以使用MyClass = type("MyClass", (object, ), dict())等动态创建类,但我找不到创建函数的方法。 I have an idea of direct line to line translation of code in python code and execution but that's not really what I want to do.我对 python 代码和执行中的代码进行直接行到行转换的想法,但这并不是我真正想做的。 So is there a way to create functions dynamically or the best I can get is something like:那么有没有办法动态创建函数,或者我能得到的最好的方法是:

foo_code = compile('def foo(): return "bar"', "<string>", "exec")
foo_func = FunctionType(foo_code.co_consts[0], globals(), "foo")

with need of translation?需要翻译吗?

Just found out the answer.才知道答案。 The best way to dynamically create the function is to not create it at all.动态创建 function 的最佳方法是根本不创建它。 It kind of conflicts with my question but still solves the problem.这与我的问题有点冲突,但仍然解决了问题。 The idea is to put a structure of a function as key in a dictionary and a line of the beginning of the function as a value.想法是将 function 的结构作为字典中的键,并将 function 开头的行作为值。 So now it is possible by structure of the function find it, execute and then return to normal execution by saving the last line of Main in advance.所以现在可以通过function的结构找到它,执行,然后通过提前保存Main最后一行返回正常执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM