Python 的with关键字
Python 的with关键字
看别人的代码时,with关键字经常会出现,博主决定梳理一下with以及python中上下文(context)的概念
1. 上下文管理器概念
Context Manager指的是python在执行一段代码前后,做的一些预处理和后处理,使得代码块运行处于一个小的环境(surrounding),出了这个小环境之后,资源释放,环境中的各种配置也失效。
例如在打开文件需要关闭,连接数据库后需要关闭连接。很多优雅第三方库也会利用上下文使得对象进入特定的某种状态。
2. with关键字
with的基本用法如下:
with EXPR as VAR:
BLOCK
其中发生了一系列过程:
- EXPR语句被执行,得到ContextManager
- 调用ContextManager.__enter__方法
- 如果有as VAR,则ContextManager.__enter__的返回值赋给VAR,否则就不管返回值
- 执行BLOCK,如果有VAR被用到,就和普通变量一样
- 调用ContextManager.__exit__方法
- __exit__有三个参数:type, value, traceback,BLOCK出异常时会得到对应值,正常情况就都为None
- __exit__返回值为True表示BLOCK中出现的异常可以忽略,False表示需要raise
3. 例子
3.1 资源操作:
class CustomOpen:
def __init__(self, filename: str):
self.__filename = filename
self.__handler = None
def __enter__(self):
print("enter......")
self.__handler = open(self.__filename)
return self.__handler
def __exit__(self, exc_type, exc_val, exc_tb):
print("exit...", exc_type, exc_val, exc_tb)
if self.__handler is not None:
self.__handler.close()
return True
with CustomOpen("hello.txt") as f:
print(f.read())
运行结果:
enter......
hello world
exit... None None None
3.2 状态维护
class CustomBrain:
def __init__(self):
self.__status = "normal"
def say(self):
if self.__status == "normal":
print("You're a great man")
elif self.__status == "special":
print("You are a very outstanding person ")
def __enter__(self):
self.__status = "special"
def __exit__(self, exc_type, exc_val, exc_tb):
self.__status = "normal"
brain = CustomBrain()
brain.say() # 普通状态
# 可以通过上下文维护一些状态
with brain:
brain.say() # 特殊状态
brain.say() # 普通状态
运行结果:
You're a great man
You are a very outstanding person
You're a great man
4. 使用contextlib简化编写
python内置的标准库contextlib可以是的代码书写更加简洁,本质是一样的。比较有用的是contextlib.contextmanager这个装饰器,被装饰的函数在yield的前面相当于__enter__,yield的后面相当于__exit__,yield本身的返回值赋给as后的变量
所以第一个示例可以这么写:
from contextlib import contextmanager
@contextmanager
def custom_open(filename: str):
print("enter......")
handler = open(filename)
yield handler
print("exit...")
handler.close()
with custom_open("hello.txt") as f:
print(f.read())
还是优雅了许多~
Python 的with关键字的更多相关文章
- Python中的关键字的用法
Python有哪些关键字 -Python常用的关键字 and, del, from, not, while, as, elif, global, or, with, assert, else, if, ...
- python的标识符&&关键字
和Java语言一样,python也有标识符和关键字.那么,你是否知道python的关键字呢?一起先从标识符了解python吧. 什么是标识符? 标识符,开发人员在开发过程中自定义的一些符号和名称. 标 ...
- python中super关键字的用法
http://python.jobbole.com/86787/ class A: def __init__(self): print "enter A" print ...
- python正则提取关键字
python使用正则表达式提取关键字 import sys reload(sys) sys.setdefaultencoding("utf-8") import re ss = & ...
- python 位置参数和关键字参数 *args **kwargs
#!/usr/bin/env pythondef foo(*args,**kwargs): print('args: {0}'.format(args)) print('kwargs {0}'.for ...
- python进阶之关键字和运算符触发魔法方法
前言 python有众多的魔法方法,它们会在满足某种条件下触发执行,掌握好魔法方法的使用,可以加快程序的运行效率,同时减少逻辑调用. 关键字与魔法方法 python的一些魔法方法是关键字触发的,即py ...
- python开发_python关键字
python3.3.2中的关键字如下: The following identifiers are used as reserved words, or keywords of the languag ...
- python语言(四)关键字参数、内置函数、导入第三方模块、OS模块、时间模块
一.可变参数 定义函数时,有时候我们不确定调用的时候会传递多少个参数(不传参也可以).此时,可用包裹(packing)位置参数(*args),或者包裹关键字参数(**kwargs),来进行参数传递,会 ...
- 怎样查看python的所有关键字
关键字是python中具有特定功能的一组词汇, 这些词汇不能用作变量名, 一般会有高亮提示, code时请小心. python的关键字其实也是python的语法核心, 掌握了所有python关键字的用 ...
随机推荐
- maven入门-- part5 本地仓库,远程仓库,私服
解读Maven在仓库中的存储路径: 1.基于groupId准备路径,将句点分隔符转成路径分隔符,就是将 "." 转换成 "/" ; example: org ...
- kbmMWClientQuery判断一个字段是否修改?
function TForm5.IsFieldChanged(aDataSet: TkbmMWCustomClientQuery; aFieldName: string): Boolean; var ...
- [转]DELL PERC 系列阵列卡选型和用法指南
引用地址 https://www.sulabs.net/?p=895 DELL PERC 系列阵列卡选型和用法指南 2018年12月29日 Su 本文缘起于一位朋友在生产服务器硬件中,使用了错误的阵列 ...
- 第十章、numpy模块
目录 第十章.numpy模块 一.导入方式 二.作用 三.通过函数创建numpy数组 四. numpy数组运算 五.重点 第十章.numpy模块 一.导入方式 import numpy as np#约 ...
- linux tty终端个 pts伪终端 telnetd伪终端
转:http://blog.sina.com.cn/s/blog_735da7ae0102v2p7.html 终端tty.虚拟控制台.FrameBuffer的切换过程详解 Framebuffer Dr ...
- Linux:fdisk
fdisk [-l] 装置名称 选项与参数: -l:输入后面接的装置所有的partition内容.若仅有fdisk -l时,则系统将会把整个系统内能够搜寻到的装置的partition均列出来 fdis ...
- vue+django前后端项目部署
一.python3的安装 1.安装python前的库环境: yum install gcc patch libffi-devel python-devel zlib-devel bzip2-devel ...
- 转 SQL连接查询语句(内、外、交叉和合并查询)
转 http://blog.csdn.net/u010011371/article/details/50596535 1.内连接 (INNER JOIN) 内连接也称自然连接,它是根据两个或多个表中的 ...
- Python的函数式编程: map, reduce, sorted, filter, lambda
Python的函数式编程 摘录: Python对函数式编程提供部分支持.由于Python允许使用变量,因此,Python不是纯函数式编程语言. 函数是Python内建支持的一种封装,我们通过把大段代码 ...
- jdbc连接数据库方式问题
1.使用service_name,配置方式:jdbc:oracle:thin:@//<host>:1521/net_grid 2.使用SID,配置方式:jdbc:oracle:thin:@ ...