Python之面向对象上下文管理协议

  析构函数:

 import time
class Open:
def __init__(self,filepath,mode='r',encode='utf-8'):
self.f=open(filepath,mode=mode,encoding=encode) def write(self):
pass def __getattr__(self, item):
return getattr(self.f,item) def __del__(self):
print('----->del')
self.f.close() f=Open('a.txt','w')
f1=f
del f print('=========>')

  上下文管理协议: 

 # with open('a.txt','r') as f:
# print('--=---->')
# print(f.read()) # with open('a.txt', 'r'):
# print('--=---->') #
class Foo:
def __enter__(self):
print('=======================》enter')
return 111111111111111 def __exit__(self, exc_type, exc_val, exc_tb):
print('exit')
print('exc_type',exc_type)
print('exc_val',exc_val)
print('exc_tb',exc_tb)
return True # with Foo(): #res=Foo().__enter__()
# pass with Foo() as obj: #res=Foo().__enter__() #obj=res
print('with foo的自代码块',obj)
raise NameError('名字没有定义')
print('************************************') print('')

 

 # import time
# class Open:
# def __init__(self,filepath,mode='r',encode='utf-8'):
# self.f=open(filepath,mode=mode,encoding=encode) # def write(self,line):
# self.f.write(line) # def __getattr__(self, item):
# return getattr(self.f,item) # def __del__(self):
# print('----->del')
# self.f.close() # def __enter__(self):
# return self.f
# def __exit__(self, exc_type, exc_val, exc_tb):
# self.f.close() # with Open('George'.txt','w') as f:
# f.write('Georgetest\n')
# f.write('Georgetest\n')
# f.write('Georgetest\n')
# f.write('Georgetest\n')
# f.write('Georgetest\n') class Open:
def __init__(self,filepath,mode,encode='utf-8'):
self.f=open(filepath,mode=mode,encoding=encode)
self.filepath=filepath
self.mode=mode
self.encoding=encode def write(self,line):
print('write')
self.f.write(line) def __getattr__(self, item):
return getattr(self.f,item) def __enter__(self):
return self def __exit__(self, exc_type, exc_val, exc_tb):
self.f.close()
return True with Open('aaaaa.txt','w') as write_file: #write_file=Open('aaaaa.txt','w')
write_file.write('123123123123123\n')
write_file.write('123123123123123\n')
print(sssssssssssssss)
write_file.write('123123123123123\n')

Python之面向对象上下文管理协议的更多相关文章

  1. python 描述符 上下文管理协议 类装饰器 property metaclass

    1.描述符 #!/usr/bin/python env # coding=utf-8 # 数据描述符__get__ __set__ __delete__ ''' 描述符总结 描述符是可以实现大部分py ...

  2. python基础----实现上下文管理协议__enter__和__exit__

    我们知道在操作文件对象的时候可以这么写 with open('a.txt') as f: '代码块' 上述叫做上下文管理协议,即with语句,为了让一个对象兼容with语句,必须在这个对象的类中声明_ ...

  3. Python系列之 - 上下文管理协议

    with obj as f: '代码块' 1.with obj ---->触发obj.__enter__(),拿到返回值 2.as f----->f=返回值. 3.with obj as ...

  4. python 面向对象编程 之 上下文管理协议

    with open('path', 'r' ,encoding='utf-8') as f: 代码块 上述就叫做上线文管理协议,即with语句,为了让一个对象兼容with语句,必须在这个对象的类中声明 ...

  5. Python上下文管理协议:__enter__和__exit__

    上下文管理器(context manager)是Python2.5开始支持的一种语法,用于规定某个对象的使用范围.一旦进入或者离开该使用范围,会有特殊操作被调用 (比如为对象分配或者释放内存).它的语 ...

  6. Python 上下文管理协议中的__enter__和__exit__基本理解

    所谓上下文管理协议,就是咱们打开文件时常用的一种方法:with __enter__(self):当with开始运行的时候触发此方法的运行 __exit__(self, exc_type, exc_va ...

  7. 用python优雅打开文件及上下文管理协议

    有次面试被问到如何优雅地打开一个文件?   那就是用with语句,调用过后可以自动关闭.   但是为什么使用with语句就可以自动关闭呢,原因就是上下文管理协议.   上下文管理协议:包含方法 __e ...

  8. python - 上下文管理协议(with + __enter__ + __exit__)

    上下文管理协议: with + __enter__ + __exit__ #上下问管理协议: #with + __enter__ + __exit__ class Test(): def __init ...

  9. Python概念-上下文管理协议中的__enter__和__exit__

    所谓上下文管理协议,就是咱们打开文件时常用的一种方法:with __enter__(self):当with开始运行的时候触发此方法的运行 __exit__(self, exc_type, exc_va ...

随机推荐

  1. Akka源码分析-Serialization

    今天我们来谈一下akka的序列化框架,其实序列化.反序列化是一个老生常谈的问题,那么我们为什么还要研究一下akka的序列化框架呢?不就是使用哪种序列化.反序列化方法的区别么?其实刚开始的时候我也是这么 ...

  2. Go基于协程的归并排序简单实现

    归并排序这个可能很多人都不知道,今天用Go语言简单的实现下,其他语言可能要基于线程来实现. //产生一个源 func ArraySource(a ...int) chan int{ out :=mak ...

  3. 例题3-4 master-mind hints

    下面先附上我的水货代码,,,,一会附上,,,刘大婶给的代码///////3ms #include<stdio.h> #include<string.h> int main() ...

  4. play framework

    Compilation errorThe file {module:docviewer}/app/controllers/PlayDocumentation.java could not be com ...

  5. for循环的阶乘

    方法一: long sum=0; long num=1; for (long i = 1; i <=20; i++) { for(long j=i;j>0;j--){ num=num*j; ...

  6. 事件模型的介绍与Button的ActionListener

    事件监听: 这是个很重要的概念,也是个很重要的模型,vb,vc都是这样用,甚至后面学的web框架也在用.    现在我们可以做很多按钮了吧,但是我们的按钮按它是没反应的,现在我们来看看怎么样才能让它有 ...

  7. Kali linux 2016.2(Rolling) 的详细安装(图文教程)附安装VMare Tools 增强工具

    写在前面的话 因读研期间,实验室团队需要,所以,接触上了Kali Linux,需去获得网络安全方面的数据,即数据和信息收集.以便为后续的数据处理和分析,准备! 用到hadoop和spark.机器学习等 ...

  8. DEV—【GridControl主从表】

    先附上效果图,不是想要这个效果的朋友就不用可以继续寻找了. DEV—GridControl制作主从表: (注:此例没有用到数据库,只是单纯的在内存中操作数据.) 写这一笔,是为了能更好的理解主从表,的 ...

  9. 三种将list转换为map的方法(传统方法、jdk8 Stream流、guava)

    三种将list转换为map的方法 - jackyrong - ITeye博客:http://jackyrong.iteye.com/blog/2158009

  10. LN : leetcode 118 Pascal's Triangle

    lc 118 Pascal's Triangle 118 Pascal's Triangle Given numRows, generate the first numRows of Pascal's ...