switch语句可以具有带参数的功能吗?

时间:2018-09-01 12:38:55

标签: python-3.x function switch-statement

我有一个正在使用的脚本,该脚本具有功能开关。

我希望在keyCodes上创建案例并执行带有参数的正确方法。    密钥代码可以是“ C”或“ P”,否则将提示“ Invalid”。

class Switcher(object):
def indirect(self, code):
    method_name = 'method_' + str(code)
    method = getattr(self,method_name, lambda: 'Invalid')
    return method()

def method_C(self,title):
    return 'method_C'  + title


def method_P(self,title):
    return 'method_P'  + title

我的main()如下:

s = Switcher()
func = s.indirect('C')
a = func("I'm at Method_C")
print(a)

在尝试将参数传递给生成的方法时出现异常

TypeError: 'str' object is not callable

与代码行有关:a = func(“我在Method_C上”)

任何想法?

1 个答案:

答案 0 :(得分:0)

在调用结果方法以将参数传递给它之前,我想调用基于1个关键参数的方法。


更清楚地说,我希望:

1. send key = 'C'.
2  the switch will select method_C as result.
3. to call the method_C with string argument (without knowing which method was 
   resulted).