python - How to call a function from a list? -


for example, have following list:

method = [fun1, fun2, fun3, fun4] 

then show menu user must select number 1-4 (len(method)). if user selects i, have use function funi. how can 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 want call function bye array a, using

>>>a[1](7) traceback (most recent call last): file "<pyshell#0>", line 1, in <module> a[2](5) typeerror: 'str' object not callable 

how can use names saved in a call functions? because every method saved in string.

let's see...

you call function fn using parens () in fn()

you access item list indexing operator [] in lst[idx]

so, combining 2 lst[idx](*args)

edit

python list indices zero-based, first item 0, second 1, etc... if user selects 1-4, you'll have subtract one.

edit

given clarification, following can done

def method1():     pass  def method2():     pass   methods = [method1, method2] 

and can use logic above. way won't have mess actual resolving string of name of function actual function.

keep in mind functions in python first class can store reference of them list (what in methods=[] line)


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -