简体   繁体   English

从函数列表中获取随机函数并调用所选函数

[英]Getting a random function from a list of functions and calling the selected function

I'm trying to create a function that I can call and it selects a random function from a list of functions and calls the selected function into action. 我正在尝试创建一个我可以调用的函数,它从函数列表中选择一个随机函数,并将所选函数调用为动作。 Is that even possible? 这甚至可能吗? Here what I have tried. 这是我尝试过的。 Which results in nothing happening. 这导致什么都没发生。

import random

def ran1(): 
    print("test1")

def ran2(): 
    print("test2") 

def ran3(): 
    print("test3") 

def ran4(): 
    print("test4")

list_functions = [ran1,ran2,ran3,ran4]

def ran_choice():
    random.choice(list_functions)

ran_choice()

Your logic is fine. 你的逻辑很好。 You just need to call the function you choose in ran_choice : 你只需要调用你在ran_choice选择的函数:

def ran_choice():
    random.choice(list_functions)()

Although, it might be easier to read as: 虽然,它可能更容易阅读:

def ran_choice():
    chosen_fn = random.choice(list_functions)
    chosen_fn()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM