2

给定一个班级

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

你如何继承它?

4

1 回答 1

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:
                ...
于 2012-12-04T22:36:34.417 回答