Python 中 If/Elif 语句的“最终”等效项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21612910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'Finally' equivalent for If/Elif statements in Python
提问by nobillygreen
Does Python have a finallyequivalent for its if/elsestatements, similar to its try/except/finallystatements? Something that would allow us to simplify this:
Python 是否有finally与其if/else语句类似的等价try/except/finally语句?可以让我们简化这个的东西:
if condition1:
do stuff
clean up
elif condition2:
do stuff
clean up
elif condition3:
do stuff
clean up
...
...
to this:
对此:
if condition1:
do stuff
elif condition2:
do stuff
elif condition3:
do stuff
...
...
finally:
clean up
Where finallywould only be called only after a condition was met and its 'do stuff' run? Conversely, if no condition was met, the finallycode would not be run.
当finally将一个条件得到满足后,只只叫其“做的东西”跑?相反,如果不满足任何条件,则finally不会运行代码。
I hate to spout blasphemy, but the best way I can describe it is there being a GOTOstatement at the end of each block of 'do stuff' that led to finally.
我讨厌吐槽亵渎神明,但我能描述它的最好方式是GOTO在导致finally.
Essentially, it works as the opposite of an elsestatement. While elseis only run if no other conditions are met, this would be ran ONLY IF another condition was met.
本质上,它与else语句相反。虽然else只有在不满足其他条件时才运行,但只有在满足另一个条件时才会运行。
采纳答案by Daniel Fairhead
It can be done totally non-hackily like this:
它可以像这样完全非hackily完成:
def function(x,y,z):
if condition1:
blah
elif condition2:
blah2
else:
return False
#finally!
clean up stuff.
In some ways, not as convenient, as you have to use a separate function. However, good practice to not make too long functions anyway. Separating your logic into small easily readable (usually maximum 1 page long) functions makes testing, documenting, and understanding the flow of execution a lot easier.
在某些方面,并不方便,因为您必须使用单独的功能。但是,无论如何都不要制作太长的功能的好习惯。将您的逻辑分成易于阅读的小函数(通常最多 1 页长)使测试、记录和理解执行流程变得更加容易。
One thing to be aware of is that the finallyclause will not get run in event of an exception. To do that as well, you need to add try:stuff in there as well.
需要注意的一件事是,finally如果发生异常,该子句将不会运行。要做到这一点,您还需要在其中添加try:内容。
回答by mhlester
Is this hideous?
这很可怕吗?
for _ in range(1):
if condition1:
do stuff
break
elif condition2:
do stuff
break
else:
finally stuff
How about this?
这个怎么样?
class NoFinally(Exception):
pass
try:
if condition1:
do stuff
raise NoFinally
elif condition2:
do stuff
raise NoFinally
except NoFinally:
pass
else:
finally
Honestly, I hate both of these
老实说,我讨厌这两个
回答by Ricardo Cárdenes
Your logic is akin to this:
你的逻辑类似于:
cleanup = True
if condition1:
do stuff
elif condition2:
do stuff
elif condition3:
do stuff
....
else:
cleanup = False
if cleanup:
do the cleanup
Ugly, but it is what you asked
丑,不过是你问的
回答by Pig
Another suggestion, which might suit you if the conditions are pre-computed.
另一个建议,如果条件是预先计算好的,它可能适合您。
if condition1:
do stuff
elif condition2:
do stuff
...
if any([condition1, condition2, ...]):
clean_up
This would be a pain if you were evaluating the conditions as part of your if statements, because in that case you would have to evaluate them a second time for the anyfunction...unless Python is smarter than I realise.
如果您将条件作为 if 语句的一部分进行评估,这将是一件痛苦的事情,因为在这种情况下,您将不得不为any函数再次评估它们……除非 Python 比我意识到的更聪明。
回答by DylanYoung
Like this:
像这样:
from .actions import stuff1, stuff2
actions={condition1: stuff1, condition2: stuff2}
for condition in actions:
if condition:
actions[condition]()
cleanup()
break
Caveats are of course that your condition keys have to be unique and hashable. You can get around this by using a different data structure.
警告当然是您的条件键必须是唯一且可散列的。您可以通过使用不同的数据结构来解决这个问题。
回答by JLT
The answer of mhlester has repetitive code, an improved version might be as follows:
mhlester的回答有重复代码,改进版可能如下:
class NoCleanUp(Exception):
pass
try:
if condition1:
do stuff
elif condition2:
do stuff
else:
raise NoCleanUp
except NoCleanUp:
pass
else:
cleanup
回答by Claus Nielsen
A little late to the party, but see the question has been active recently.
聚会有点晚了,但看到这个问题最近很活跃。
Usually I would make a context manager like this
通常我会做一个这样的上下文管理器
class CleanUp(object):
class Cancel(Exception):
pass
def __init__(self, f_cleanup):
self.f_cleanup = f_cleanup
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
cancelled = exception_type and issubclass(exception_type, self.__class__.Cancel)
if not cancelled:
self.f_cleanup()
return not exception_type or cancelled
def cancel(self):
raise self.__class__.Cancel
And then you can use it like this
然后你可以像这样使用它
def cleanup():
print "Doing housekeeping"
with CleanUp(cleanup) as manager:
if condition1:
do stuff
elif condition2:
do stuff
else:
manager.cancel()
回答by Durgeoble
you can use try
你可以使用尝试
try:
if-elif-else stuff
finally:
cleanup stuff
the exception is raised but the cleanup is done
引发异常但已完成清理

