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)
Python函数是一类对象:您可以不调用它们而按名称引用它们,然后在以后调用它们。在
在最初的代码中,您调用了这三种方法,然后在结果中随机选择。这里我们随机选择一个函数,然后调用它。在
差不多——试试这个吧:
这会将函数本身分配到
random_function_selector
列表中,而不是调用这些函数的结果。然后使用choice
得到一个随机函数,并调用它。在只是为了好玩:
注意,如果您真的想在真正定义函数之前定义函数选择列表,那么您可以使用附加的间接层来实现(尽管我不推荐使用它,但据我所见,这样做没有任何好处…):
^{pr2}$相关问题 更多 >
编程相关推荐