06 #### `__enter__、__exit__` 用来对上下文管理,可以使用这两个方法

# __enter__、__exit__ 用来对上下文管理
class content:

    def __init__(self, filepath, mode):
        self.filepath = filepath
        self.mode = mode
        self.encoding = 'utf-8'
        self.fileobject = None

    def __enter__(self):
        # 可以用来:打开文件、链接、数据操作
        self.fileobject = open(self.filepath, self.mode, encoding=self.encoding)  # 得到一个文件对象,然后进行返回
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # 关闭 or 结束
        self.fileobject.close()  # 操作完成后,进行关闭文件

    def send(self):
        self.fileobject.write('发送\n')  # 通过获取的文件对象进行写操作

    def read(self):
        self.fileobject.write('发送222\n')


# 写法1
obj = content('test', 22)

# 如果需要支持 with,需要在类方法中,增加__enter、__exit__方法,否则报错

with obj as xxx:  # with的是一个对象,只要with这个对象时,自动执行__enter 方法,

    print(xxx)  # 如果enter中return 123,此时as xxx 中的:xxx  就等于123

# 写法2
# 也支持下面的这种写法:
with content('test.txt', 'a') as obj:
    print(obj)  # 当with里面的代码执行完后,自动执行 __exit__ 方法
    # 此时执行的 obj.send/obj.read 都 在 __enter__ 之后
    obj.send()
    obj.read()

posted @   jhchena  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示