0

I'm stucking with the process of user input a string to execute a function without using dictionary of functions. Specifically, I defined a class

class Myclass():
    def __init__(self, df):
        ...
        return

    def function_1(self, **kwargs):
        return result
    
    def function_2(self, **kwargs):
        return result
    ...

User from the frontend give an input in string, like "function_1". I wonder how can I execute the method of class right away using this string as below

# From frontend
receive = Input() # receive will be the string right now when user choose "function_1"
print(receive)
>>> "function_1"

# From backend
result = Myclass(df).function_1()

Solution that I have tried

I have tried to use

def MyFunction(dataframe, userFunctionChoose:str, **kwargs):
    tasks = {}
    def task(task_fn):
       tasks[task_fn.__name__] = task_fn

    @task
    def function_1(dataframe):
       return result
   
    @task
    def function_2(dataframe):
       return result
    return tasks[userFunctionChoose]()

result = MyFunction(dataframe, "function_1")

Although it's worked properly, however, I still need to create a class for other use-cases, and it contains more than 50 methods inside.

With the input string, how can I make the Myclass run the required method as nested function?

deceze
  • 510,633
  • 85
  • 743
  • 889
ShanN
  • 831
  • 1
  • 9
  • 20
  • 2
    It seems you are looking for the [getattr()](https://docs.python.org/3.11/library/functions.html#getattr) function – quamrana Jul 03 '23 at 09:44
  • @quamrana ```getattr()``` still not gives me the final result, it is just the detail address of the function on memory ``>. Here I need it returns the numpy array as I designed – ShanN Jul 03 '23 at 10:47
  • 1
    Yes, `getattr()` can be used to return a bound method. You should call that method. – quamrana Jul 03 '23 at 10:49
  • I've added another duplicate which may be closer to what you are looking for, – quamrana Jul 03 '23 at 11:04

0 Answers0