with的用法

class DBManager(object):
     def __init__(self):
    pass

  def __enter__(self):     
     print('__enter__')
     return self

  def __exit__(self, exc_type, exc_val, exc_tb):
     print('__exit__')
     return True

def getInstance():
    return DBManager()

with getInstance() as dbManagerIns:              使用with时会调用 __enter__ 方法,结束后调用__exit__方法
  print('with demo')

posted on 2021-01-26 16:41  Plyc  阅读(95)  评论(0编辑  收藏  举报

导航