随机选择函数

2024-05-18 14:50:35 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法随机选择一个函数?在

示例:

from random import choice

def foo():
    ...
def foobar():
    ...
def fudge():
    ...

random_function_selector = [foo(), foobar(), fudge()]

print(choice(random_function_selector))

上面的代码似乎执行所有3个函数,而不仅仅是随机选择的函数。正确的方法是什么?在


Tags: 函数代码fromimport示例foodeffunction
3条回答
from random import choice
random_function_selector = [foo, foobar, fudge]

print choice(random_function_selector)()

Python函数是一类对象:您可以不调用它们而按名称引用它们,然后在以后调用它们。在

在最初的代码中,您调用了这三种方法,然后在结果中随机选择。这里我们随机选择一个函数,然后调用它。在

差不多——试试这个吧:

from random import choice
random_function_selector = [foo, foobar, fudge]

print(choice(random_function_selector)())

这会将函数本身分配到random_function_selector列表中,而不是调用这些函数的结果。然后使用choice得到一个随机函数,并调用它。在

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)

只是为了好玩:

注意,如果您真的想在真正定义函数之前定义函数选择列表,那么您可以使用附加的间接层来实现(尽管我不推荐使用它,但据我所见,这样做没有任何好处…):

^{pr2}$

相关问题 更多 >

    热门问题