允许可选参数的Python开关大小写

允许可选参数的Python开关大小写,python,Python,我知道python中没有开关用例,可以使用字典来代替。但是,如果我想将参数传递给函数zero(),但不传递参数给one(),该怎么办?我没有发现任何与此相关的问题 def zero(number): return number == "zero" def one(): return "one" def numbers_to_functions_to_strings(argument): switcher = { 0: zero, 1:

我知道python中没有开关用例,可以使用字典来代替。但是,如果我想将参数传递给函数zero(),但不传递参数给one(),该怎么办?我没有发现任何与此相关的问题

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()需要接受(可选)参数?

您可以使用


我假设你指的是你调用的函数的固定参数。如果是这种情况,只需将函数包装到另一个使用相关参数调用它的函数中:

switcher = {
    0: lambda: zero("not zero"),
    1: one,
    2: lambda: "two",
}
您可以使用相同的方法从
numbers\u到\u functions\u到\u strings
调用传递可选值:

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

如果我理解正确的话,这里有一个不导入任何内容也不导入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))
打印(开关箱(“a”)(10))

11.0

打印(开关盒(“b”)(10,3))

66.0

打印(开关箱(“ddd”)(10))

十,


您要传入哪个参数
zero
lambda
functools。部分
可以工作。重新构造,使映射中的所有函数至少接受相同的参数,即使它们不都使用它们。
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))