2016-04-15 50 views
1

我知道python中没有开关大小写,并且可以使用字典代替。但是如果我想将参数传递给函数zero()但是没有参数传递给one()呢?我没有发现任何与此有关的问题。允许可选参数的Python开关大小写

def zero(number): 
    return number == "zero" 

def one(): 
    return "one" 

def numbers_to_functions_to_strings(argument): 
    switcher = { 
     0: zero, 
     1: one, 
     2: lambda: "two", 
    } 
    # Get the function from switcher dictionary 
    func = switcher.get(argument, lambda: "nothing") 
    # Execute the function 
    return func() 

什么是实现这个最简单的方法,而不必将它们分为两种情况?我认为func()需要采用(可选)参数?

+0

你在'zero'中传递了哪个参数? – AKS

+1

'lambda'或'functools.partial'可以工作。重构,使地图中的所有函数至少*接受*相同的参数,即使它们不全部使用它们。 – jonrsharpe

回答

1

你可以使用partial

from functools import partial 

def zero(number): 
    return number == "zero" 

def one(): 
    return "one" 

def numbers_to_functions_to_strings(argument): 
    switcher = { 
     0: partial(zero, argument), 
     1: one, 
     2: lambda: "two", 
    } 

    func = switcher.get(argument, lambda: "nothing") 
    return func() 
1

我假设你的意思是一个固定的参数要呼叫的功能。如果是这样的话,只是包装的功能在与相关的参数调用它的另一个功能:

switcher = { 
    0: lambda: zero("not zero"), 
    1: one, 
    2: lambda: "two", 
} 

您可以使用相同的方法从numbers_to_functions_to_strings呼叫通过传递一个可选的arument:

def numbers_to_functions_to_strings(argument, opt_arg="placeholder"): 
    switcher = { 
     0: lambda: zero(opt_arg), 
     1: one, 
     2: lambda: "two", 
    } 
0

如果我正确地理解了这种情况,那么在不导入任何内容并且没有lambda的情况下,可以选择这种方式。您可以直接导航到必要的方法,你已经拥有的切换外:

def fa(num): 
    return num * 1.1 
def fb(num, option=1): 
    return num * 2.2 * option 
def f_default(num): 
    return num 

def switch(case): 
    return { 
     "a":fa, 
     "b":fb, 
    }.get(case, f_default) # you can pass 

print switch("a")(10) # for Python 3 --> print(switchcase("a")(10)) 
print switch("b")(10, 3) # for Python 3 --> print(switchcase("b")(10, 3)) 

打印(switchcase( “A”)(10))

11.0

打印(switchcase(” b “)(10,3))

66.0

打印(switchcase(” DDD“)(10))