【发布时间】:2017-10-12 20:09:19
【问题描述】:
我无法为这个问题找到合适的标题,所以请原谅我。
我班上的很多方法都是这样的:
def one_of_many():
# code to determine `somethings`
for something in somethings:
if self.try_something(something):
return
# code to determine `something_else`
if self.try_something(something_else):
return
…
其中self.try_something 返回True 或False。
有没有办法用类似的方式来表达:
def one_of_many():
# code to determine `somethings`
for something in somethings:
self.try_something_and_return(something) # this will return from `one_of_many` on success
# code to determine `something_else`
self.try_something_and_return(something_else) # this will return from `one_of_many` on success
…
我一直在摆弄装饰器和上下文管理器来实现这一点,但没有成功,但我仍然相信“一定有更好的方法!”。
【问题讨论】:
-
您可以像这样将
if self.try_something(something): return放在一行中,方法是将return移到同一行,但大多数情况下它并不能真正提高可读性。试图让一个代表其调用者返回的try_something_and_return方法会更糟。 -
@Davit 我希望它只返回(如在第一个代码 sn-p 中)。
标签: python python-decorators program-flow