Python: 练习 with语句和上下文管理器 __enter__() 和 __exit__()方法 @contextmanager 装饰器Python: 练习 with语句和上下文管理器 __enter__() 和 __exit__()方法 @contextmanager 装饰器Python: 练习 with语句和上下文管理器 __enter__() 和 __exit__()方法 @contextmanager 装饰器Python: 练习 with语句和上下文管理器 __enter__() 和 __exit__()方法 @contextmanager 装饰器
  • 首页
  • 博客
  • 文件
  • 书签
  • 分析
  • 登录
Search
Generic filters

Python: 练习 with语句和上下文管理器 __enter__() 和 __exit__()方法 @contextmanager 装饰器

Published by admin at 2022年6月16日
Categories
  • Practice
Tags
from contextlib import contextmanager


class OpenFile(object):
    def __init__(self, file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):
        self.file = file
        self.mode = mode

    def __enter__(self):
        print("OpenFileA上文方法")
        self.fd = open(self.file, self.mode)
        return self.fd

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("OpenFileA下文方法")
        self.fd.close()


@contextmanager
def open_file(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):
    print("open_file上文方法")
    fd = open(file, mode)
    yield fd
    print("open_file下文方法")
    fd.close()

with OpenFile("test.py", "r") as fd:
    print(fd.read())
with open_file("test.py", "r") as fd:
    print(fd.read())

发表回复 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Categories

  • 猫
  • Python
  • MySQL
  • Django
  • Html/CSS
  • JavaScript
  • Vue
  • RegExp
  • php
  • Practice
  • Virtualization
  • Linux
  • Windows
  • Android
  • NAS
  • Software
  • Hardware
  • Network
  • Router
  • Office
  • WordPress
  • SEO
  • English
  • Games
  • Recipes
  • living
  • Memorandum
  • Essays
  • 未分类

归档

©2015-2022 Alaica Blog support@alaica.com