【问题标题】:Can a switch statements have functions with arguments?switch 语句可以有带参数的函数吗?
【发布时间】:2018-09-01 12:38:54
【问题描述】:

我有一个正在处理的脚本,它具有带功能的开关。

我希望在 keyCodes 上创建案例并使用参数执行正确的方法。 键码可以是“C”或“P”,否则会提示“无效”。

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("I'm at Method_C")

有什么想法吗?

【问题讨论】:

  • s.indirect('C') 返回调用方法的结果,而不是方法本身,因此将其命名为func 并尝试调用它是没有意义的。
  • 得到你!它需要在间接方法中处理。那么如何切换带有参数的函数呢?
  • 请尽量解释清楚你打算做什么,可能有更简单的方法。

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


【解决方案1】:

我想在调用结果方法向其传递参数之前根据 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).

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    相关资源
    最近更新 更多