简体   繁体   English

根据全局变量设置选择不同的功能

[英]Selecting different functions based on global variable setting

I want to try out different random number generators but not change my code everywhere.我想尝试不同的随机数生成器,但不要到处更改我的代码。

So I define a global variable rG所以我定义了一个全局变量 rG

rG = None

# and provide an intialisation routine

def initrG(randomGenerator):
    global rG
    if (randomGenerator == "secret"):
        rG = randbelow
    elif (randomGenerator == "mple"):
        rG = random.randint
    elif (randomGenerator == "numpyrandint"):
        rG = numpy.random.randint
    else:
        rG = None

Then use rG like in然后使用 rG 就像在

randomNumber = rg (10) 

calling the different generators dependent on the initial call of the initrG routine.根据initrG 例程的初始调用调用不同的生成器。

Two issues:两个问题:

a) Somehow the assignment of the functions seems not to work. a)不知何故,功能的分配似乎不起作用。

b) the functions have different number of parameters. b) 函数有不同数量的参数。 How should this be handled.这个应该怎么处理。

It generally would be clearer to have rG be a class with state that determines which algorithm to use, but you specifically asked to not have to rewrite code.通常让 rG 是一个具有确定使用哪种算法的状态的类会更清楚,但您特别要求不必重写代码。

Here's a potential way to do it, using functools.partial to create small wrapper functions.这是一种可能的方法,使用functools.partial创建小型包装器函数。 Alternatively create the wrapper functions yourself, it'll be a little clearer to see what each is doing.或者自己创建包装函数,看看每个函数在做什么会更清楚一些。

from functools import partial
from secrets import randbelow
import numpy as np
import random

rG = None

def initrG(randomGenerator):
    global rG
    if (randomGenerator == "secret"):
        rG = randbelow
    elif (randomGenerator == "mple"):
        rG = partial(random.randint, 0)
    elif (randomGenerator == "numpyrandint"):
        rG = partial(np.random.randint, 0)
    else:
        rG = None

initrG("secret")
print(rG(10), rG.__module__)
initrG("mple")
print(rG(10), rG.func.__module__)
initrG("numpyrandint")
print(rG(10), rG.func)

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

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