随机选择一个函数,并在Python中使用适当的属性调用它

问题描述 投票:0回答:1

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语句来检查选择了哪个随机函数,然后基于该语句选择适当的属性?还是有捷径?

python function random
1个回答
2
投票

您可以在选项列表中将所需的参数包含在函数中。

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)())
© www.soinside.com 2019 - 2024. All rights reserved.