• python 约束与异常处理


    一、类的约束

      1、约束就是对类的约束。其实就是父类对子类进行约束,子类必须要写xxx方法。

      2、抽象:就是当我们没法对一个功能或者一个属性进行精确的表述,一般都采用抽象的方式给出。

        (1)抽象类的书写规范

    from abc import ABCMeta,abstractmethod
    # 引入抽象方法的模块
    
    class Base(metaclass=ABCMeta): #定义抽象类 maetaclass=ABCmeta
        @abstractmethod#抽象方法的关键字
        def 方法(self):
            pass

        (2)抽象类相关的知识点:

          a:一个类包含抽象方法,一定属于抽象类

          b:抽象类,可以包含正常的方法(实例方法、类方法、静态方法)

          c:抽象类不能创建对象

          d:如果子类未对父类的抽象方法进行重写,该类也是一个抽象类,无法创建对象

          f:接口,类中全都是抽象方法

    from abc import ABCMeta,abstractmethod
    # 引入抽象方法的模块
    
    class Base(metaclass=ABCMeta): #定义抽象类 maetaclass=ABCmeta
        @abstractmethod#抽象方法的关键字
        def he(self):
            pass
        def chi(self):
            print("吃什么")
    
    class Foo(Base):
        def shui(self):
            print ("睡你麻痹")
    f=Foo()#Can't instantiate abstract class Foo with abstract methods he
    f.shui()
    # 只要类包含了抽象方法就不能创建对象

     

      2、python中约束有的两种方式:(贴吧登陆)

        (1)使用抽象类和抽象方法

    from abc import ABCMeta,abstractmethod
    class Base(metaclass=ABCMeta):
        @abstractmethod #定义一个抽象的login方法
        def login(self):
            pass
    class Normal(Base):
        def login(self):
            print("普通用户登录")
    class Memer(Base):
        def login(self):
            print("吧务登陆")
    class Admin(Base):
        def login(self):
            print("管理员登录")

        (2)使用抛出异常,并且抛出的异常时NotImplementError。这样比较专业,并且错误比较明确。

    #如果子类没有重写父类的方法,执行了父类的方法则抛出异常
    class Base:
       def login(self):
            raise NotImplementedError("你没有重写该方法,滚回去重写")
    class Normal(Base):
        def login(self):
            print("普通用户登录")
    # class Memer(Base):
    #     def login(self):
    #         print("吧务登陆")
    class Memer(Base):
        pass
    class Admin(Base):
        def login(self):
            print("管理员登录")
    n=Normal()
    m=Memer()
    a=Admin()
    n.login()
    m.login()#NotImplementedError: 你没有重写该方法,滚回去重写
    a.login()

    二、异常处理

      1、格式: 

    try:
        '''进行操作'''
    except Exception as e:#Exception是异常的父类,可以捕获所有的异常
        '''捕获异常后,给予提示语'''
    else:
        '''try中没有出现错误,执行这里的操作'''
    finally:
        '''不管出不出错都会执行这里的操作'''

      解读:程序先执行try中的操作,如果出错了,就会走到except里面,进行相应的操作,如果没有出错,就直接执行else里面的操作,不管出不出错都会执行最后的finally.

      2、抛出异常

        (1)关键字 raise

    def cul(a,b):
        if (type(a)==int or type(a)==float)and (type(b)==int or type(b)==float):
            return a+b
        else:
            raise Exception("请给我int或者float")#抛出异常,异常Exception
    ret=cul(3,"麻辣烫")#Exception: 请给我int或者float

        (2)自定义异常  

          实现:定义一个异常继承Exception就可以实现自定义异常了(Exception是异常的基类,)    

    class GenderException(Exception):#定义了一个性别异常
        pass
    
    class Person:
        def __init__(self,name,gender):
            self.name=name
            self.gender=gender
    
        def got_nan_yushi(self):
            '''
            x洗澡
            :return:
            '''
            if self.gender=="":
                print("欢迎光临")
            else:
                raise GenderException("性别错了") #抛出自定义异常

      3、异常处理

        (1)处理除数不能是0的异常

    # ZeroDivisionError
    try: #把需要处理的对象放入其中
        print(10/0)
    except ZeroDivisionError as e:
        print("0不能做除数") 
    # 异常处理结果显示:0不能做除数

         (2)获取错误信息 :traceback (目的主要是方便程序员排查错误) 

    import traceback #插入堆栈模块
    # traceback这个模块可以获取到我们每个⽅法的调用信息
    try: #把需要处理的对象放入其中
        print(10/0)
    except ZeroDivisionError as e:
        val=traceback.format_exc()#获取堆栈信息
        print("0不能做除数")
        print()
        print(val)
    # 异常处理结果显示:0不能做除数
    结果:
    0不能做除数
    
    Traceback (most recent call last):
      File "E:/qishi/Day19 约束/04异常处理.py", line 79, in <module>
        print(10/0)
    ZeroDivisionError: division by zero

     三、日记处理

      1、基本步骤

        1. 导入logging模块.
        2. 简单配置⼀下logging
        3. 出现异常的时候(except). 向⽇志⾥写错误信息

      2、配置信息如下    

    logging.basicConfig(filename='x1.txt',
    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    level=10) # 当前配置表示 10以上的分数会被写⼊⽂件
    # # 日记
    # 1、导入logging模块
    # 2、简单配置;一下logging
    # 3、出现异常的时候,向日记里面写错误信息
    import logging
    import traceback
    # filename: ⽂件名
    # format: 数据的格式化输出. 最终在⽇志⽂件中的样⼦
    # 时间-名称-级别-模块: 错误信息
    # datefmt: 时间的格式
    # level: 错误的级别权重, 当错误的级别权重⼤于等于leval的时候才会写⼊⽂件
    logging.basicConfig(filename='x1.txt',
    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    level=20) # 当前配置表示 10以上的分数会被写⼊⽂件
    # CRITICAL = 50
    # FATAL = CRITICAL
    # ERROR = 40
    # WARNING = 30
    # WARN = WARNING
    # INFO = 20
    # DEBUG = 10
    # NOTSET = 0
    # logging.critical("我是critical") # 50分. 最贵的
    # logging.error("我是error") # 40分logging.warning("我是警告") # 警告 30
    # logging.info("我是基本信息") # 20
    # logging.debug("我是调试") # 10
    # logging.log(2, "我是⾃定义") # ⾃定义. 看着给分
    
    
    try:
        ret=10/0
    except ZeroDivisionError as e:
        print("正在写入日记")
        logging.error(traceback.format_exc())
        print("写入完毕")

      3、实例:产生10个错误,记录下来

    import logging
    import traceback
    logging.basicConfig(filename
    ='x1.txt', format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=20) # 当前配置表示 20以上的分数会被写⼊⽂件 class JackError(Exception):#自定义异常 pass for i in range(10): try: if i%3==0: raise FileExistsError("文件不在押") elif i%3==1: raise KeyError("按错了") else: raise JackError("Jack错了") except FileExistsError as e: val=traceback.format_exc() logging.error(val) print("文件丢失") except KeyError as e: val=traceback.format_exc() logging.error(val) print("瞎jb按") except JackError as e: val=traceback.format_exc() logging.error(val) except Exception: val=traceback.format_exc() logging.error(val) print("其他错误") 

          

    log文件
    2018-11-12 18:43:50 - root - ERROR -日记: Traceback (most recent call last): File "E:/qishi/Day19 约束/日记.py", line 44, in <module> raise FileExistsError("文件不在押") FileExistsError: 文件不在押 2018-11-12 18:43:50 - root - ERROR -日记: Traceback (most recent call last): File "E:/qishi/Day19 约束/日记.py", line 46, in <module> raise KeyError("按错了") KeyError: '按错了' 2018-11-12 18:43:50 - root - ERROR -日记: Traceback (most recent call last): File "E:/qishi/Day19 约束/日记.py", line 48, in <module> raise JackError("Jack错了") JackError: Jack错了 2018-11-12 18:43:50 - root - ERROR -日记: Traceback (most recent call last): File "E:/qishi/Day19 约束/日记.py", line 44, in <module> raise FileExistsError("文件不在押") FileExistsError: 文件不在押 2018-11-12 18:43:50 - root - ERROR -日记: Traceback (most recent call last): File "E:/qishi/Day19 约束/日记.py", line 46, in <module> raise KeyError("按错了") KeyError: '按错了' 2018-11-12 18:43:50 - root - ERROR -日记: Traceback (most recent call last): File "E:/qishi/Day19 约束/日记.py", line 48, in <module> raise JackError("Jack错了") JackError: Jack错了 2018-11-12 18:43:50 - root - ERROR -日记: Traceback (most recent call last): File "E:/qishi/Day19 约束/日记.py", line 44, in <module> raise FileExistsError("文件不在押") FileExistsError: 文件不在押 2018-11-12 18:43:50 - root - ERROR -日记: Traceback (most recent call last): File "E:/qishi/Day19 约束/日记.py", line 46, in <module> raise KeyError("按错了") KeyError: '按错了' 2018-11-12 18:43:50 - root - ERROR -日记: Traceback (most recent call last): File "E:/qishi/Day19 约束/日记.py", line 48, in <module> raise JackError("Jack错了") JackError: Jack错了 2018-11-12 18:43:50 - root - ERROR -日记: Traceback (most recent call last): File "E:/qishi/Day19 约束/日记.py", line 44, in <module> raise FileExistsError("文件不在押") FileExistsError: 文件不在押

  • 相关阅读:
    css基础教程
    网页加载-上下幕布分开
    Vue-Aixos
    webpack学习
    Vue、Element 路由跳转,左侧菜单高亮显示,页面刷新不会改变当前高亮菜单
    Vue知识概括
    JSON.parse() 与 JSON.stringify()
    Bootstrap4 样式笔记
    ES6基础语法
    V-model 双向绑定的原理是什么?
  • 原文地址:https://www.cnblogs.com/angle6-liu/p/9947251.html
Copyright © 2020-2023  润新知