问题
I wrote a program using many functions (def name():).
These function are summed at the end of code like:
a()+b()+c()+d()+e()
In what way I can do this:
program: >>>a,b,c,d,e are optional fuctions, which one of these functions you want to use in the calculation?
user: >>>a,b,d
and the program just bring those chosen functions in program.
I did search a lot but I could not find sth like this. Thank you for your help.
回答1:
You could use a dictionary in the following way.
def a():
return 2 + 3
def b():
return 3 - 2
def c():
return 2*3
def d():
return 2/3
dic = {}
dic['a'] = a
dic['b'] = b
dic['c'] = c
dic['d'] = d
funcs = str(raw_input("which functions would you like to use?: "))
funcs = funcs.split(',')
result = 0
for i in funcs:
result += dic[i]()
print result
回答2:
You can use getattr() to get the functions:
import sys
def a():
return 1
def b():
return 2
def c():
return 3
sum = 0
# Assume user input of 'a' & 'c'
for name in ['a', 'c']:
#
# Get the function and call it...
#
sum += getattr(sys.modules[__name__], name)()
print('sum: {}'.format(sum))
来源:https://stackoverflow.com/questions/49437572/optional-function-to-choose-for-user