初学python的朋友会疑惑,为什么python没有switch,这不是所有语言的标配吗?
分支太多,用if/elif/else代码看起来很难受呀?太不美好了?
为什么要这样设计呢?我想看python作者的回答是最直接的。
https://docs.python.org/2/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python
Why isn’t there a switch or case statement in Python?
You can do this easily enough with a sequence of
if... elif... elif... else
. There have been some proposals for switch statement syntax, but there is no consensus (yet) on whether and how to do range tests. See PEP 275 for complete details and the current status.For cases where you need to choose from a very large number of possibilities, you can create a dictionary mapping case values to functions to call. For example:
def function_1(...): ... functions = {'a': function_1, 'b': function_2, 'c': self.method_1, ...} func = functions[value] func()For calling methods on objects, you can simplify yet further by using the
getattr()
built-in to retrieve methods with a particular name:def visit_a(self, ...): ... ... def dispatch(self, value): method_name = 'visit_' + str(value) method = getattr(self, method_name) method()It’s suggested that you use a prefix for the method names, such as
visit_
in this example. Without such a prefix, if values are coming from an untrusted source, an attacker would be able to call any method on your object.
大体意思,简单的用if/elif/else都可以解决,复杂一点用字典可以完美的漂亮的实现,而且是很好的做法。
def function_1(...):
pass
def function_2(...):
pass
def function_3(...):
pass
functions = {'a': function_1, 'b': function_2, 'c': self.function_2, ...}
func = functions[value]
func()