1

I want to call two functions inside a python function. But that call is dependent on a variable. Both functions have the same function. Is there a way to change the function name using a variable ?

What I have as functions :

def a1_suffix(self,option):
  return "does something"
def a2_suffix(self,option):
  return "does something else"

Then the function that I use to call these functions

def myfunction(self,option):
  somevar = "could be a1 or a2"
  self.somevar+"_suffix"(option)

The last line should be equivalent to :

self.a1_suffix(option) or self.a2_suffix(option)

I tried doing that alone but It doesn't seem to work. I have a TypeError 'str' not callable

What's the way to reach this mechanism ?

nismotri
  • 87
  • 2
  • 12
Snowfire
  • 171
  • 9

1 Answers1

2

Create a dict of your functions and use it to dispatch using somevar:

class MyClass:
    def a1_suffix(self, option):
        return "does something"

    def a2_suffix(self, option):
        return "does something else"

    def myfunction(self, somevar, option):
        functions = {"a1": self.a1_suffix, "a2": self.a2_suffix}
        func = functions[somevar]
        return func(option)
AKX
  • 152,115
  • 15
  • 115
  • 172