optional function to choose for user

核能气质少年 提交于 2019-12-14 03:08:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!