Skip to main content
 首页 » 编程设计

python之python 'switches' (dict) 应该调用里面的每个函数吗

2025年05月04日15落叶无声

我正在尝试使用 python 开关编写一些代码,按照建议在 dict 中模拟:Replacements for switch statement in Python? [第二个答案,尼克]

我测试的时候,不知为什么里面的函数都被调用了,试了一段简单的代码,看看哪里出了问题,问题又重复了。见:

def switch(f): 
    print('Switch got: ', f) 
    var = { 
        1: func1(), 
        2: func2(), 
        3: func3() 
        }.get(f,False) 
    return var 
 
def func3(): 
    fb = 'Func3 called' 
    print(fb) 
    return fb 
 
def func1(): 
    rsp = 'Func1 called' 
    print(rsp) 
    return rsp 
 
def func2(): 
    rsp = 'Func2 called' 
    print(rsp) 
    return rsp 
 
var = switch(1) 
print(var) 

我的预期返回是:

Switch got:  1 
Func1 called 

相反,我得到了:

Switch got:  1 
Func1 called 
Func2 called 
Func3 called 
Func1 called 

我从中得到的是 python 似乎在调用正确的键(示例中的 1)之前运行 dict 中的每个函数。

这是 Python 中的预期行为吗?

有没有办法只调用与键对应的函数?

请您参考如下方法:

Is this the expected behavior in Python?

是的。

Is there a way around, where only the function that corresponds to the key is called?

在创建调度指令时不要实际调用函数:

def switch(k): 
    print('Switch got: ', k) 
    func = { 
        1: func1, 
        2: func2, 
        3: func3, 
    }.get(k, bool) 
    var = func() 
    return var