-1

I have an ensemble of functions: func1, func2, func3, ... funcN. Only 1 function will be used based on the user input, e.g. if user put '1', only func1 will be used. So far what I did is to put these function in a branch:

class FunctionEnsembles:
    def __init__(self,select_funcion):
        self.function_to_select=select_function
    def function_to_use(self):
        if self.function_to_select=='1':
           func1...
        elif self.function_to_select=='2':
           func2...
        ...

Apparently this is not efficient. When the class gets instantiated, e.g FunctionEnsemble myfunc('1'), the definition all the functions are involved. If one calls myfunc.function_to_use, it will go through all the branches, which is not desirable. What I want to do is : function is selected once the class FunctionEnsembleis instantiated, while unwanted functions are not touched.

How to effectively achieve this ? Many thanks.

Andy
  • 49,085
  • 60
  • 166
  • 233
Void
  • 153
  • 4
  • 12

1 Answers1

1

Python functions are first-class objects; you can put them in a list:

functions = [None, func1, func2, func3, ...]
functions[int(self.function_to_select)]()

or in a dictionary:

functions = {
    'selection1': func1,
    'selection2': func2,
    'selection3': func3,
}

functions[self.function_to_select]()

Lists work great if your function_to_select variable is really a number in a sequence, dictionaries are great for anything else that is hashable (such as strings).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks, the dictionary approach is promising. But I don't think I can put this dictionary in __init__(...) function. I am guessing I have to put this dictionary under the function_to_use(self)? – Void Mar 28 '14 at 17:00
  • @Void: Are these global functions or bound methods on `self`? – Martijn Pieters Mar 28 '14 at 17:01
  • @Void: for global functions, I'd create the dictionary as a global too. For methods, I'd create the dictionary in `__init__` so I have access to `self` to grab the bound methods from, then store that dictionary on `self`. – Martijn Pieters Mar 28 '14 at 17:02
  • The functions are not global. I tried to do this: `def __init__(self,input): funcdict={} funcdict['1']=func1 funcdict['2']=func2`,`def func1(self):blabla`, I stumble upon this error: `global name 'func1' is not defined` . – Void Mar 28 '14 at 17:04
  • @Void: If the functions are *methods*, then you want to store `self.func1`, etc. – Martijn Pieters Mar 28 '14 at 17:32