官方文档: Design and History FAQ - Python 2.7.16 documentation
你可以通过一系列的方式轻松地做到这一点. 比如 if... elif... elif... elsePEP 275 和字典.
对于需要从大量可能性中进行选择的情况, 您可以创建一个字典映射案例值到要调用的函数. 例如:
- def function_1(...):
- ...
- functions = {'a': function_1,
- 'b': function_2,
- 'c': self.method_1, ...}
- func = functions[value]
- func()
要调用对象上的方法, 可以使用 getattr() 内置函数来检索具有特定名称的方法, 从而进一步简化 :
- def visit_a(self, ...):
- ...
- ...
- def dispatch(self, value):
- method_name = 'visit_' + str(value)
- method = getattr(self, method_name)
- method()
建议您为方法名称使用前缀, 例如 visit_在此示例中. 如果没有这样的前缀, 如果值来自不受信任的来源, 攻击者就可以调用对象上的任何方法.
来源: http://www.mzh.ren/why-isn-t-there-a-switch-or-case-statement-in-python.html