你可以用
collections.abc
并将你的类划分为子类
F
从
Generator
(
manual pages
)如果你实施
进入
和
出口
,您的实例将是生成器,并且还具有上下文管理器支持:
from collections.abc import Generator
class F(Generator):
def __init__(self):
self.__my_generator = self._my_generator()
next(self.__my_generator) # prime the generator
def _my_generator(self):
while True:
v = yield 42
print('generator received ', v)
# context manager interace:
def __enter__(self):
return self
def __exit__(self, *exc):
print('exit')
# Generator interface:
def send(self, value):
return self.__my_generator.send(value)
def throw(self, typ, value=None, traceback=None):
return self.__my_generator.throw(typ, value, traceback)
with F() as o:
while True:
a = o.send(2)
print('I received ', a)
印刷品:
generator received 2
I received 42
...etc.