学习笔记(18):21天通关Python(仅视频课)-管道输入与with语句

立即学习:https://edu.csdn.net/course/play/24797/282198?utm_source=blogtoedu

# import sys
# for i in sys.stdin:
#     print(i)

class TestWith:
    def __init__(self, tag):
        self.tag = tag
        print('构造函数——init——')

    def __enter__(self):
        print('运行__enter__方法tag=%s' % self.tag)
        return '返回enter方法结果'

    '''
    异常信息
    exc_type:异常类型
    exc_val:异常传入的value
    exc_tb:异常的traceback
    '''

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_tb:
            print('此处有异常')
        else:
            print('程序运行正常')


with TestWith('testWith') as re:
    print('re:%s' % re)
    print('开始')
    # raise Exception(2, '错误')
    print('结束')

with open('test45.py', 'r', True, 'utf-8') as f:
    for i in f:
        print(i, end='')
发布了25 篇原创文章 · 获赞 4 · 访问量 598

猜你喜欢

转载自blog.csdn.net/happyk213/article/details/105219969