[英]How do you use a string from a list to call a function with the same name, in Python?
I wasn't able to find a satisfying answer anywhere so I decided to ask.我在任何地方都找不到令人满意的答案,所以我决定问一下。
Let's say we have a global counter and a global list假设我们有一个全局计数器和一个全局列表
counter=0
list=["function1","function2",..."functionN"]
we also we have those functions defined:我们还定义了这些函数:
def function1():
pass
def function2():
pass
.
.
.
def functionN():
pass
I have an interface with a button, every time I press it, the global counter increments.我有一个带按钮的界面,每次按下它,全局计数器都会增加。 Depending on the number, I need to call a different function.根据数量,我需要调用不同的函数。 I can implement this with if and elif but I don't think it's that smart.我可以用 if 和 elif 来实现这个,但我认为它不是那么聪明。 Is there a way I can call those functions using the list?有没有办法可以使用列表调用这些函数?
Example例子
when counter=0=>list[0]=>the string is 'function1'=> call function1()当 counter=0=>list[0]=> 字符串是 'function1'=> 调用 function1()
press button again再次按下按钮
counter=1=>list[1]=>the string is 'function2' => call function2() counter=1=>list[1]=>字符串是'function2'=>调用function2()
You can call a function by its name like this:您可以按名称调用函数,如下所示:
locals()["myfunction"]()
or:或者:
globals()["myfunction"]()
or if its from another module like this:或者如果它来自像这样的另一个模块:
import foo
getattr(foo, 'myfunction')()
Or if it suits your use case, just use a list of functions instead of a list of strings:或者,如果它适合您的用例,只需使用函数列表而不是字符串列表:
def func1():
print("1")
def func2():
print("2")
def func3():
print("3")
def func4():
print("4")
some_list=[func1, func2, func3, func4]
# call like this
for f in some_list:
f()
# or like this
some_list[0]()
Similar to what @chepner said, I would approach the problem that way.与@chepner 所说的类似,我会以这种方式解决问题。
Potentially storing the functions in a dictionary and looking up the function based on the counter:可能将函数存储在字典中并根据计数器查找函数:
def function():
print('function 1 called')
def function2():
print('function 2 called')
counter = 0
functions = {
1: function,
2: function2
}
Then:然后:
function_to_call = functions[counter + 1]
and now that when function_to_call()
is called it would print function 1 called
现在,当function_to_call()
被调用时,它会打印function 1 called
This is how I would think about approaching the problem.这就是我如何看待解决问题的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.