0

I have a dictionary that has function names, i. e.

dict = {
    'family1' :
        ['classA(param1=555','classB(param1=777)'] }

Now I would like to call the methods of the classes like so:

myclass = dict['family1'][0]
myclass.method()

However, I'm getting str object does not have the method() (but it definitely has it, however I seems the myclass is not recognized and stays a string.

BEST ANSWER: Remove '' from ['functioname'] so that the dictionary does not have strings but actual function references in it. Then calls will not reference a string but a function reference.

petezurich
  • 9,280
  • 9
  • 43
  • 57
  • Possible duplicate of [Calling a function of a module by using its name (a string)](https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string) – Jeppe Jun 09 '19 at 19:32
  • 3
    you should check lambda or functools.partial. How many parameters your functions have? – Jean-François Fabre Jun 09 '19 at 19:32
  • If `functionname` is an actual function in the scope, what about a lambda? `lambda *args: functionname(*args, param1=6398)` – N Chauhan Jun 09 '19 at 19:33
  • @Jean-FrançoisFabre: Not more than 5 for any of the functions that I use. –  Jun 09 '19 at 19:35
  • Could you be looking for `eval`? https://docs.python.org/3/library/functions.html#eval – Baleato Jun 09 '19 at 19:35
  • please provide more real functions. You want to bind a parameter to a function and leave the others settable? use `lambda` or `functools.partial` and don't use strings. – Jean-François Fabre Jun 09 '19 at 19:36
  • @Jean-FrançoisFabre: Parameters could be left out, if need be, however I'd like to iterate through a dictionary of classes names and call methods on them one by one depending on which class is selected. Within those calls I need to call methods. –  Jun 09 '19 at 19:44

2 Answers2

1

You should place actual functions in your dictionary. Functions and lambdas in Python are first class types so you can use them in data.

functions = {
    'family1' :
        [lambda:classB(param1=555), lambda:classB(param1=777)],
    'family2' :
        [lambda:functionname(param1=6981),lambda:functionname(param1=9333)] }

def functionname(param1): print(param1)

functions['family2'][0]() # prints 6981

functions['family1'][0]() # returns classB(param1=555)
Alain T.
  • 40,517
  • 4
  • 31
  • 51
1
dict = {
    'family1' :
        ['classA(param1=555)','classB(param1=777)'] }

class classA():

    def __init__(self,param1):
        self.param=param1
    def method(self):
        print("A",self.param)

class classB():

    def __init__(self, param1):
        self.param = param1
    def method(self):
        print("B",self.param)

myclass = dict['family1'][0]
eval(myclass).method()
myclass = dict['family1'][1]
eval(myclass).method()
Jainil Patel
  • 1,284
  • 7
  • 16