zoukankan      html  css  js  c++  java
  • __enter__和__exit__的用法

    #__enter__与__exit__是成对出现的,一般是在进行with obj时才会触发它们

    class Open:
    def __init__(self,filepath,mode='r',encode='utf-8'):
    self.f=open(filepath,mode=mode,encoding=encode)
    # self.filepath =filepath
    # self.mode =mode
    # self.encoding =encode
    def __getattr__(self, item):
    return getattr(self.f,item)
    def __enter__(self):
    return self #如果是self.f,则在f.write(),就不会执行__getattr__方法

    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

    def __del__(self):
    print('-->')
    self.f.close()

    #f =Open('a.txt','w')
    with Open('a','w') as f:
    print(f)
    f.write('aaaaa ') #f.write(item),因为对象f没有write()方法,就执行__getattr__方法
    #即getattr(f.x,write)(item)
    f.write('bbbb')
  • 相关阅读:
    dex文件格式三
    神庙逃亡破解分析
    MySQL优化
    Redis AOF和RDB
    KD树
    关系型和非关系型数据库
    数据库实现分布式锁
    单点登录
    数据库树形结构查询
    层次遍历递归和非递归方法
  • 原文地址:https://www.cnblogs.com/IQ-Python/p/6764106.html
Copyright © 2011-2022 走看看