Python 的with exp() as obj:
语法对任何具有“强制”进入和退出方法的对象都很有吸引力——考虑到人们尝试扩展obj.__del__
但结果不佳的情况以及所有这些情况,它似乎指向使用__enter__
and__exit__
方法。
我首先想到的是带有进入和退出方法的状态机;无论如何处理都是基本的,但使状态机的实际实现非常简单。
class State(object):
def __init__(self, strategy):
self.strategy = strategy
def __enter__(self, *args):
return self
def __call__(self, *args, **kwargs):
self.strategy(self, *args, **kwargs)
def __exit__(self, *args):
clean_up_things()
...
...
...
def state_handle():
states = (State(foo), State(bar), State(eggs))
for state in states:
with state() as s:
what_ever(s)
然而,似乎人们通常将语法视为子句和/或语句with XXX as YYY
的替代品,而我不断发现的一件事是 Python 社区喜欢知道在实现某个功能时会发生什么。所以如果用错误的咒语来解决正确的问题,它仍然是错误的答案。try/finally
yield
Python 是否with...as
出于特定原因故意为生成器保留语法,或者是否可以根据需要应用此语法?如果有目的,那目的是什么?(我在 PEP 8 中几乎没有提到with/as
,如果那是正确的地方看的话)