Python中的switch case语句允许可选参数。

4

我知道在Python中没有switch case语句,可以使用字典代替。但是如果我想将参数传递给函数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()需要带上(可选)参数?


你在 zero 中传递了哪个参数? - AKS
1
lambdafunctools.partial都可以使用。重新构造映射,使得其中所有函数至少接受相同的参数,即使它们并不都使用它们。 - jonrsharpe
3个回答

8

你可以使用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()

7

如果我正确理解了这个案例,那么在不导入任何内容和不使用lambda的情况下,您可以直接访问已在switch语句外部的必要方法来完成该操作:

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)的结果

10


1
我假设你是指对你调用的函数传递一个固定参数。如果是这种情况,只需将这些函数包装在另一个函数中,该函数使用相关参数调用它:
switcher = {
    0: lambda: zero("not zero"),
    1: one,
    2: lambda: "two",
}

你可以使用相同的方法通过numbers_to_functions_to_strings调用来传递可选参数:
def numbers_to_functions_to_strings(argument, opt_arg="placeholder"):
    switcher = {
        0: lambda: zero(opt_arg),
        1: one,
        2: lambda: "two",
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接