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. Is there a way I can call those functions using the list?
Example
when counter=0=>list[0]=>the string is 'function1'=> call function1()
press button again
counter=1=>list[1]=>the string is 'function2' => call 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.
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
This is how I would think about approaching the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.