1

I have a long list of functions that needs to be executed based on user input

I want a way to do this without a long if else statement

Thanks in advance this will save a lot of time

def function1(a,b):
    return a+b

def function2(a,b):
    return a-b
.
.
.
there a are many functions like this
.
.
.

class marks:
    def __init__(self,w,b):
        self.w=w
        self.b=b

    def execute(self,function):
        I WANT TO KNOW THIS PART

m=marks(50,30)

m.execute("function2") should perform function2 and print
m.execute("function45") should perform function45 and print
Akila Uyanwatta
  • 543
  • 1
  • 4
  • 11
  • probably `getattr(object_instance, method_name)` [docs](https://docs.python.org/3/reference/datamodel.html#object.__getattr__) – ti7 May 27 '21 at 04:04

3 Answers3

2

You can use locals()

def execute(self, function):
    locals()[function]()

BUT you also need a way to pass arguments to those functions like

def execute(self, function, *args):
    locals()[function](*args)

More info here: Calling a function of a module by using its name (a string)

ted
  • 13,596
  • 9
  • 65
  • 107
2

Set up a dictionary in the style action = {'keyword1':function1,'keyword2':function2...} then for user input entry you can check the input with entry in action and activate with action[entry]().

Joffan
  • 1,485
  • 1
  • 13
  • 18
  • Note that this allows multiple synonyms for a given action if desired, `{'key1':function1, 'key1alt':function1, 'key1alt2':function1, 'key2':function2...}` etc. – Joffan May 27 '21 at 08:41
0

Try using the eval function:

names = {"function1": function1, "function2": function2 ...}
func = input('which function do you want to call')
print(eval(func, names))