python with使用的一些例子

while this might look like magic, the way Python handles with is more clever than magic. The basic idea is that the statement after with has to evaluate an object that responds to an __enter__() as well as an __exit__() function.

After the statement that follows with is evaluated, the __enter__() function on the resulting object is called. The value returned by this function is assigned to the variable following as. After every statement in the block is evaluated, the __exit__() function is called.


例子如下:

class RedirectionStdoutTo:
	def __init__(self, fd):
		self.out_new = fd
	def __enter__(self):
		self.old_out = sys.stdout
		sys.stdout = self.out_new
	def __exit__(self):
		sys.stdout = self.old_out

with open('Logfile') as fd:
	with RedirectionStdoutTo(fd):
		do_something()

这里open函数返回的file object对象实现了__enter__和__exit__方法,RedirectionStdoutTo()实例也实现了__enter__和__exit__方法;第一个with返回了file object对象供后续使用,第二个未明确在as后引用


这里自行写了一个小类实现tcp连接的关闭:

import socket
class mysocket:
    def __init__(self, sockfd):
        self.sockfd = sockfd 
    def __enter__(self):
        print "Enter"
    def __exit__(self, para1, para2, para3):
        print "Exit"
        self.sockfd.close()
        
        
sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockfd.connect(("www.taobao.com", 80))

with mysocket(sockfd):
    pass
        



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值