For example, I have the following list:
method = [fun1, fun2, fun3, fun4]
Then I show a menu where the user must select a number from 1-4 ( len(method)
). If the user selects i
, I have to use the function funi
. How can I do that?
Eg.
A=['hello','bye','goodbye']
def hello(n):
print n**2
def bye(n):
print n**3
def goodbye(n):
print n**4
If I want to call the function bye
by the array A, using
>>>A[1](7)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
A[2](5)
TypeError: 'str' object is not callable
How can I use the names saved in A
to call my functions? because every method is saved in a string.
Let's see...
You call a function fn by using parens () as in fn()
You access an item from a list by the indexing operator [] as in lst[idx]
So, by combining the two lst[idx](*args)
EDIT
Python list indices are zero-based, so for the first item is 0, the second 1, etc... If the user selects 1-4, you'll have to subtract one.
EDIT
Given the clarification, the following can be done
def method1():
pass
def method2():
pass
methods = [method1, method2]
And you can use the logic above. This way you won't have to mess with actual resolving the string of a name of the function to the actual function.
Keep in mind that functions in python are first class so you can store a reference of them to a list (what we do in methods=[]
line)
In your list are not functions but strings (which have "randomly" the same name as the functions). Just put the functions inside the list:
def hello():
pass
mylist = [hello]
mylist[0]()
If you need the name of a function you can use a.__name__
eg
def hello():
pass
mylist = [hello]
print("Available functions:")
for function in mylist:
print(function.__name__)
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.