Answer the question
In order to leave comments, you need to log in
How to call a function whose name is written in a string in Python 3?
The question is this: I enter the name of the function and I just want this name to execute the function.
And I don't want to create a couple dozen if/elif/else to iterate over all the functions in the code.
I don't know how to do this!
Please describe how to do this in more detail.
call_func = input("Введите название функции чтобы её вызвать: ")
if call_func[0] == '$':
call_func = call_func[1:]
call_func()
Answer the question
In order to leave comments, you need to log in
In general, the very formulation of the kagbe question hints at the architectural problems of this approach. But, if you decide the issue "on the forehead", then here is the most logical option:
call_func = input("Введите название функции чтобы её вызвать: ")
locals()[call_func]()
call_func
. If they are defined in the namespace of the module, and call_func
- deeper, in a function or method, then globals()
. And if they are generally somewhere in other modules that may not be imported in advance, then you need to dig aside importlib.import_module
, but this is certainly an overkill. eval
, but also not good.
def func1(text):
return text
def func2():
return ""
functions = {'func1':func1, 'func2':func2}
functions['ваш input']()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question