GitHub 博客园 Nanakon

上下文管理器

python with as语法

 

import contextlib

class Pipeline(object):
    def _publish(self, objects):
        print('-------start')
        print(objects)
        # Imagine publication code here
        pass
    def _flush(self):
        print('-------end')
        # Imagine flushing code here
        pass

    @contextlib.contextmanager
    def publisher(self):
        try:
            yield self._publish
        finally:
            self._flush()
        
pipeline = Pipeline()
with pipeline.publisher() as publisher:
    publisher([1, 2, 3, 4])
    print('-----------')

 

通过一条 with 语句同时打开两个文件

with open("file1", "r") as source, open("file2", "w") as destination:
    destination.write(source.read())

 

posted on 2016-10-31 15:38  jzm17173  阅读(65)  评论(0编辑  收藏  举报

导航

轻音