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

# -*- 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')

猜你喜欢

转载自blog.csdn.net/weixin_43650411/article/details/86552446
今日推荐