【发布时间】: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