您的位置:首页 > 编程语言 > Python开发

# with语句自定义(上下文管理器)__Python

2019-01-19 15:01 260 查看
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 19 14:32:51 2019

@author: Fergus
"""
class Testwith_1(object):
def __enter__(self):
print('run')

def __exit__(self, exc_type, exc_val, exc_tb):
print('test is run')

class Testwith(object):
'''
with 包含了 初始化__enter__ & 结束__exit__ 方法
'''

def __enter__(self):
print('run now')

def __exit__(self, exc_type, exc_val, exc_tb):
if exc_tb is None:
print('exit normal')
else:
print('has error %s' %exc_tb)

if __name__ == '__main__':

with Testwith_1():
print('不加判断前')

with Testwith():
print('test')
raise NameError('testNameError')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: