使用contextlib.contextmanager继承

时间:2012-12-04 22:35:27

标签: python contextmanager

给出一个班级

class SomeClass:
    @contextlib.contextmanager
    def on_connection(self, target_terminal, source_terminal):
        ...
        yield
        ...

你如何从中继承?

1 个答案:

答案 0 :(得分:2)

可以将contextlib.contextmanager模式与with块组合在一起,以引入超类'上下文管理器:

class SomeDerivedClass(SomeClass):
    @contextlib.contextmanager
    def on_connection(self, target_terminal, source_terminal):
        with super().on_connection(target_terminal, source_terminal):
            ...
            try:
                yield
            finally:
                ...