All,
I have below functions
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_004(para):
tmp = para - 2
return tmp
those functions only have different in function names while the algorithm line e.g. "tmp = para - 2", besides that, the rest part are all same.
So, may I know if I can doing something like this:
def $fooname (para): # $ is borrowed try to say fooname is a variable
$alog # $algo is also variable
return tmp
lst = [
['tmp = para + 2', "foo_001"],
['tmp = para * 2', "foo_002"],
['tmp = para / 2', "foo_003"],
['tmp = para - 2', "foo_004"],
]
In runtime, I can use lst[0][0] assign to $algo and using lst[0][1] assign to $fooname in somehow and I can invoke the function via the lst[0][x] inside of the lst?
Thanks!
==========
Thanks for you reply, more specific for my problem here.
file 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, I want save them in a text file?
- I found there's common part in function defination is "tmp = #algo",can I extract them out form those definations while can I define the functions in runtime? I want something like this:
file 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)())