字典以不同的参数在方法之间切换

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

Python中缺少case / switch语句的常见解决方法是使用字典。我正在尝试使用它在如下所示的方法之间进行切换,但是这些方法具有不同的参数集,目前尚不清楚如何容纳它。

def method_A():
    pass
def method_B():
    pass
def method_C():
    pass
def method_D():
    pass
def my_function(arg = 1):
    switch = {
        1: method_A,
        2: method_B,
        3: method_C,
        4: method_D
    }
    option = switch.get(arg)
    return option()
my_function(input)  #input would be read from file or command line

如果我理解正确,字典键将与不同的方法相关联,因此调用my_function随后将调用与我作为输入提供的键相对应的方法。但这没有机会将任何参数传递给这些后续方法。我可以使用默认值,但这并不是重点。可供选择的方法是嵌套if-else语句供选择,这不存在此问题,但可以说可读性和优雅程度较低。

感谢您的帮助。

python-3.x
1个回答
1
投票

诀窍是将*args, **kwargs传递到my_function并将** kwargs传递到您选择的函数上并在那里进行评估。

def method_A(w):
    print(w.get("what"))  # uses the value of key "what"
def method_B(w):
    print(w.get("whatnot","Not provided")) # uses another keys value

def my_function(args,kwargs):
    arg = kwargs.get("arg",1)  # get the arg value or default to 1
    switch = {
        1: method_A,
        2: method_B,
    }
    option = switch.get(arg)
    return option(kwargs)

my_function(None, {"arg":1, "what":"hello"} ) # could provide 1 or 2 as 1st param
my_function(None, {"arg":2, "what":"hello"} ) 

输出:

hello
Not provided

有关更多信息,请参见Use of *args and **kwargs。>>

© www.soinside.com 2019 - 2024. All rights reserved.