首页 > 编程语言 >python当中自定义上下文管理器

python当中自定义上下文管理器

时间:2022-10-20 11:13:49浏览次数:50  
标签:__ 管理器 自定义 python self filename mode def

在python当中,我们知道with的用法,是一种上下文管理机制。比如with open(file,'w') as f:  这种方法下,就集成了open和close.我们也可以自定义一个上下文管理器。

方法一:

class Content(object):
    def __init__(self,filename,mode,encoding='utf-8'):
        self.filename = filename
        self.mode = mode
        self.encoding = encoding

    def __enter__(self):
        self.f = open(self.filename,self.mode)
        return self.f

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()

    def do_something(self):
        print('hello world')

with Content('content_test.txt','a') as f:
    f.write('bruce 是个美男')
View Code

注意事项:

  必须要有__enter__和__exit__两个魔术方法。

 

方法二:

import contextlib

@contextlib.contextmanager
def hander_file(filename,mode):
    print('---before yield---')
    f = open(filename,mode)
    yield f
    print('---after yield ---')
    f.close()

with hander_file('.\content_test.txt','a') as f:
    print('hander_file')
    f.write("hello world \n")

使用 contextlib.contextmanager 装饰器,可以将一个函数变为一个上下文管理器,不过要求这个被修饰的函数必须为一个生成器。所以,函数中药有yield的存在。

 

标签:__,管理器,自定义,python,self,filename,mode,def
From: https://www.cnblogs.com/shaoyishi/p/16809028.html

相关文章

  • 第六章Python实训
    test6-1    test6-2    test6-3    test6-4    test6-5    test6-6    ......
  • python中的Xpath的安装及使用
    Xpath是一门在XML文档中查找信息的语言。XPath可用来在XML文档中对元素和属性进行遍历。XPath是W3CXSLT标准的主要元素,并且XQuery和XPointer都构建于XPath表......
  • python DeepRacer超参
    超级参数(Hyperparameters)参考了这篇文章https://rambo.blog.csdn.net/article/details/120643653训练的过程:1、小车根据经验操作或者随机操作,跑出界或者跑完一圈后为......
  • python DeepRacer生成最优路径和速度
    DeepRacer生成最优路径和速度获取赛道数据从github下载:https://github.com/aws-deepracer-community/deepracer-race-dataraw_data里边就是赛道数据,reinvent2018:是rein......
  • python-opencv cv.imshow 错误
    本文平台windows报错信息: cv2.imshow('imshow',img))Thefunctionisnotimplemented.RebuildthelibrarywithWindows,GTK+2.xorCocoasupport.Ifyouare......
  • python实验报告(第六周)
    一、实验目的1.掌握如何创建并调用一个函数,以及如何进行参数传递和指定函数的返回值等。2.掌握变量的作用域和匿名函数。二、实验环境python版本:3.10(64-bit)三、实验内......
  • python使用selenium操作浏览器
    重复的操作令手工测试苦不堪言,于是自动化测试出现了!作为web应用里最出名的自动化测试工具,selenium让web应用的测试轻松了很多。今天我们就来简单的介绍一下一些简单的sele......
  • DAPR in Python
    最近在部署项目时,用到了DAPR,记录一下。一、安装     本地安装  https://docs.dapr.io/zh-hans/getting-started/install-dapr-cli/      docker内安......
  • 二、Python入门
    一、第一句Python代码编辑/scripts目录下编辑hello.py输入1print("hello,word")执行hello.py 即python3/scripts/hello.pypython内部执行过程如下: ......
  • 【Python】判断列表或字典中是否存在key值
    第一种in方法,即列出所有key值查询是否在里面a={"name":"1","value":"2"}if"name"ina.keys():print("存在")else:print("不存......