在运行时生成Python函数并使用字符串名称调用它们
foo.py
def foo_001(para): tmp = para + 2 return tmp
def foo_002(para): tmp = para * 2 return tmp
def foo_003(para): tmp = para / 2 return tmp
...
def foo_100(para): tmp = #complex algo, return tmp
main.py
from foo import *
fun_name = ["foo_001","foo_002","foo_002" ... "foo_100"]
src = 1
rzt = []
for i in fun_name:
rzt.extent(eval(i)(src))
这是我的问题:
我可以在运行时获取 fun_name 列表吗,因为我想将它们保存在文本文件中?
我发现函数定义中有一个共同的部分,即“tmp = #algo”,我可以从这些定义中提取它们吗?我可以在运行时定义这些函数吗?我想要这样的东西:
foo.py
def foo_factory():
# in somehow
return adict #function_name/function pair
template = [
["foo_001","tmp = para + 2"],
["foo_002","tmp = para * 2"],
["foo_002","tmp = para + 2"],
...
["foo_100","tmp = #complex algo"]
main.py
from foo import *
dic = foo_factory(template)
fun_name = dic.keys()
src = 1
rzt = []
for i in fun_name:
rzt.extent(eval(i)(src))
#or
rzt.extent(dic(i)())
foo.py
def foo_001(para): tmp = para + 2 return tmp
def foo_002(para): tmp = para * 2 return tmp
def foo_003(para): tmp = para / 2 return tmp
...
def foo_100(para): tmp = #complex algo, return tmp
main.py
from foo import *
fun_name = ["foo_001","foo_002","foo_002" ... "foo_100"]
src = 1
rzt = []
for i in fun_name:
rzt.extent(eval(i)(src))
here is my question:
can I get the fun_name list in runtime, because I want save them in a text file?
I found there's common part in function defination which is "tmp = #algo", can I extract them out form those definations and can I define those functions in runtime? I want something like this:
foo.py
def foo_factory():
# in somehow
return adict #function_name/function pair
template = [
["foo_001","tmp = para + 2"],
["foo_002","tmp = para * 2"],
["foo_002","tmp = para + 2"],
...
["foo_100","tmp = #complex algo"]
main.py
from foo import *
dic = foo_factory(template)
fun_name = dic.keys()
src = 1
rzt = []
for i in fun_name:
rzt.extent(eval(i)(src))
#or
rzt.extent(dic(i)())
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您不想输入整个地图,请使用装饰器来枚举函数。
Use a decorator to enumerate the functions if you don't feel like typing out the whole map.