随机选择一个函数 [英] Choosing a function randomly

查看:18
本文介绍了随机选择一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to choose a function randomly?

示例:

from random import choice

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

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

print(choice(random_function_selector))

上面的代码似乎执行了所有 3 个函数,而不仅仅是随机选择的一个.这样做的正确方法是什么?

The code above seems to execute all 3 functions, not just the randomly chosen one. What's the correct way to do this?

推荐答案

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

print choice(random_function_selector)()

Python 函数是一等对象:您可以按名称引用它们,而无需调用它们,然后再调用它们.

Python functions are first-class objects: you can refer to them by name without calling them, and then invoke them later.

在您的原始代码中,您调用了所有三个,然后在结果中随机选择.这里我们随机选择一个函数,然后调用它.

In your original code, you were invoking all three, then choosing randomly among the results. Here we choose a function randomly, then invoke it.

这篇关于随机选择一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆