在运行时生成Python函数并使用字符串名称调用它们

发布于 2024-09-28 21:20:05 字数 1108 浏览 7 评论 0原文

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))  

这是我的问题:

  1. 我可以在运行时获取 fun_name 列表吗,因为我想将它们保存在文本文件中?

  2. 我发现函数定义中有一个共同的部分,即“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:

  1. can I get the fun_name list in runtime, because I want save them in a text file?

  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

长梦不多时 2024-10-05 21:20:05
fnmap = {
  'foo_001': foo_001,
  'foo_002': foo_002,
  'foo_003': foo_003,
}

print fnmap['foo_002'](3)

如果您不想输入整个地图,请使用装饰器来枚举函数。

fnmap = {
  'foo_001': foo_001,
  'foo_002': foo_002,
  'foo_003': foo_003,
}

print fnmap['foo_002'](3)

Use a decorator to enumerate the functions if you don't feel like typing out the whole map.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文