开发者

Syntax to call random function from a list [duplicate]

开发者 https://www.devze.com 2023-02-20 14:49 出处:网络
This question already has answers here: Choosing a function randomly (5 answers) Closed 4 years ago. From this thread:
This question already has answers here: Choosing a function randomly (5 answers) Closed 4 years ago.

From this thread: How do I perform a random event in Python by picking a random variable?

I learned that it's possible to put some functions into a list, and by using random.choice(), call one of them to generate a random event.

I'm interested in doing this because I'm writing a fairly small text based game as part of a beginner's tutorial.

But when I write what I think will give me the desired result(that is, just one of the functions being called and printing its string:

import random

def func_test_1():
    print "This is func_test_1."

def func_test_2():
    print "This is func_test_2."

def func_test_3():
    print "This is func_test_3."

my_list = [func_test_1(), func_test_2(), func_test_3()]

random.choice(my_list)

I get this result:

C:\Windows\system32\cmd.exe /c python random_func.py

This is func_test_1.

This is func_test_2.

This is func_test_3.

Hit any key to close this window...

Which is all three functions being called and printing.

Could someone help me out with the correct syntax to do this? T开发者_运维知识库hank you.


With the parentheses you call the function. What you want is assigning them to the list and call the choice later:

my_list = [func_test_1, func_test_2, func_test_3]
random.choice(my_list)()


Firstly, when you do my_list = [func_test_1(), func_test_2(), func_test_3()] you store function results, not functions in the list. Do my_list = [func_test_1, func_test_2, func_test_3] instead and then call random function. Like this:

my_list = [func_test_1, func_test_2, func_test_3]
random.choice(my_list)()


Functions are objects in Python.

If you refer to them just by their name (without the parentheses, which do actually call the function!), you refer to the underlying function objects. You can re-bind them, inspect them .. or store a reference to them in a list.

mylist = [test_func_1,test_func_2,..]

At this point, none of the functions has been executed. You can then use random.choice to pick a function from the list and invoke it using ():

  • mylist[0]() calls the first function in the list
  • random.choice(mylist)() calls a random function
0

精彩评论

暂无评论...
验证码 换一张
取 消