Choosing a function randomly的答案告诉我们如何使用random.choice
从列表中选择并调用随机函数。
但是如果列表中的函数具有不同的属性怎么办?如何调用具有适当属性的函数?
示例:
from random import choice
def fun_1():
...
def fun_2(x: int):
...
def fun_3(y: bool):
...
my_integer = 8
my_boolean = True
random_function_selector = [fun_1, fun_2, fun_3]
print(choice(random_function_selector)(???))
功能fun_1
没有属性。每当选择fun_2
时,我都想用my_integer
调用它,而当选择fun_3
时,我想用my_boolean
调用它。
我在最后一行的括号中放什么?
我是否必须依靠if
语句来检查选择了哪个随机函数,然后基于该语句选择适当的属性?还是有捷径?
您可以在选项列表中将所需的参数包含在函数中。
from random import choice
def fun_1():
...
def fun_2(x: int):
...
def fun_3(y: bool):
...
my_integer = 8
my_boolean = True
random_function_selector = [(fun_1,) (fun_2, my_integer) (fun_3, my_boolean)]
f, *args = choice(random_function_selector)
print(f(*args))
或者,您可以定义进行各种调用的0参数函数包装的列表。
from functools import partial
random_function_selector = [partial(fun_1), partial(fun_2, my_integer), partial(func_3, my_boolean)]
print(choice(random_function_selector)())