飘逸的python - 两种with语句实现方法
第一种是实现上下文管理器协议,即魔法方法__enter__和__exit__。
class Foo:
def __enter__(self):
print 'in' def __exit__(self, type, value, trace):
print 'out'
定义了之后,就可以这样来使用
with Foo():
print 'do something'
输出:
in
do something
out
第二种是使用contextlib模块
from contextlib import contextmanager
@contextmanager
def Foo():
print 'in'
yield
print 'out'
飘逸的python - 两种with语句实现方法的更多相关文章
- python两种生成md5的方法
一. 使用md5包 import md5 src = 'this is a md5 test.' m1 = md5.new() m1.update(src) print m1.hexdigest() ...
- Python 两种获取文件大小的方法
import os r=os.path.getsize("/root/catbird1.stl") f=open("/root/catbird1.stl",&q ...
- Python_两种导入模块的方法异同
Python中有两种导入模块的方法 1:import module 2:from module import * 使用from module import *方法可以导入独立的项,也可以用from m ...
- C#两种创建快捷方式的方法
C#两种创建快捷方式的方法http://www.cnblogs.com/linmilove/archive/2009/06/10/1500989.html
- HTTP/HTTPS GET&POST两种方式的实现方法
关于GET及POST方式的区别请参照前面文章:http://www.cnblogs.com/hunterCecil/p/5698604.html http://www.cnblogs.com/hunt ...
- iOS - UITableView中有两种重用Cell的方法
UITableView中有两种重用Cell的方法: - (id)dequeueReusableCellWithIdentifier:(NSString *)identifier; - (id)dequ ...
- 两种ps切图方法(图层/切片)
两种Ps切图方法 一. 基础操作: a) Ctrl++ 放大图片,ctrl - -缩小图片 b) 按住空格键space+,点击鼠标左键,拖动图片. c) 修改单位,点击编辑 ...
- Eclipse中SVN的安装步骤(两种)和使用方法
Eclipse中SVN的安装步骤(两种)和使用方法 一.给Eclipse安装SVN,最常见的有两种方式:手动方式和使用安装向导方式.具体步骤如下: 方式一:手动安装 1.下载最新的Eclipse,我的 ...
- 【转】python 三种遍历list的方法
[转]python 三种遍历list的方法 #!/usr/bin/env python # -*- coding: utf-8 -*- if __name__ == '__main__': list ...
随机推荐
- [python 基础] Class 一些基本概念
class example(object): data1 = '' date2 = "" def __init__(self, para): self._function1() d ...
- SQL Server中各个系统表的作用
sysaltfiles 主数据库 保存数据库的文件 syscharsets 主数据库 字符集与排序顺序 s ...
- Linux进程间通信——使用流套接字
前面说到的进程间的通信,所通信的进程都是在同一台计算机上的,而使用socket进行通信的进程可以是同一台计算机的进程,也是可以是通过网络连接起来的不同计算机上的进程.通常我们使用socket进行网络编 ...
- BootStrap框架写的致敬乔布斯的网页
http://codepen.io/Gabyler/pen/oxjRYj <div class="container"> <div class="jum ...
- #include <boost/asio.hpp>
TCP服务端和客户端 TCP服务端 #include <iostream> #include <stdlib.h> #include <boost/asio.hpp> ...
- poj 3253 Fence Repair(模拟huffman树 + 优先队列)
题意:如果要切断一个长度为a的木条需要花费代价a, 问要切出要求的n个木条所需的最小代价. 思路:模拟huffman树,每次选取最小的两个数加入结果,再将这两个数的和加入队列. 注意priority_ ...
- Apple Mach-O Linker Warning 警告解决的方法
此警告解决的方法: 项目名字 -> targets -> Build Settings -> search path 把里面无用的东西 点 减号 删掉 即可了. $(function ...
- TreeView(C#)无限目录树代码片段
#region 绑定客户树 protected void bindTreeView() { TreeView1.Nodes.Clear(); string userid = Session[" ...
- 字符串对比.net String.EndsWith方法 (String)
string str="web/abc.aspx"; if(str.EndsWith("abc.aspx")) { 此方法将 value 与位于此实例末尾.与 ...
- UVA 12545 Bits Equalizer
题意: 两个等长的字符串p和q,p有‘0’,‘1’,‘?’组成,q由‘0’,‘1’组成.有三种操作:1.将‘?’变成0:2.将‘?’变成‘1’:3.交换同一字符串任意两个位置上的字符.问有p变到q最少 ...