from random import choice
#Step 1: define some functions
def foo():
pass
def bar():
pass
def baz():
pass
#Step 2: pack your functions into a list.
# **DO NOT CALL THEM HERE**, if you call them here,
#(as you have in your example) you'll be randomly
#selecting from the *return values* of the functions
funcs = [foo,bar,baz]
#Step 3: choose one at random (and call it)
random_func = choice(funcs)
random_func() #<-- call your random function
#Step 4: ... The hypothetical function name should be clear enough ;-)
smile(reason=your_task_is_completed)
只是为了好玩:
请注意,如果您真的想在实际定义函数之前定义函数选择列表,您可以通过额外的间接层来做到这一点(尽管我不推荐它 - 这样做没有任何优势我可以看到...):
def my_picker():
return choice([foo,bar,baz])
def foo():
pass
def bar():
pass
def baz():
pass
random_function = my_picker()
result_of_random_function = random_function()