异常 巩固3

1.with open("文件路径","模式") as fp:
    操作
进入时 调用 __enter__ 方法
    def __enter__(self):
        print("开始执行 with 方法")
退出时 调用 __exit__ 方法
    def __exit__(self,type,value,traceback):
        print("退出 with 方法")
2.文件操作方法:
    打开、读取、关闭
    d = open('a','r')
    d.read()
    d.close()
3.可以自己定义异常,继承 Exception 类


程序:
# 查看 with 执行的方法
class sth(object):

    def __enter__(self):
        print("开始执行 with 方法")

    def __exit__(self,type,value,traceback):
        print("退出 with 方法")

with sth( ) as fp:
    # with 自动关闭文件
    pass


# 自定义异常
class myException(Exception):
    # 继承 Exception
    def __init__(self,error,msg):
        self.args = (error,msg)
        self.error = error
        self.msg = msg
try:
    raise myException(1,'my exception')
except Exception as e :
    print(str(e))
    # (1, 'my exception')

2020-04-12

posted @ 2020-04-12 12:56  CodeYaSuo  阅读(86)  评论(0编辑  收藏  举报