python-day19(约束和异常处理)

一. 类的约束

  1. 抛出异常: NotImplementedError

  2. 抽象类

    from abc import ABCMeta, abstractmethod

    class Base(metaclass = ABCMeta) : 抽象类

      @abstractmethod

      def 方法(self): pass

    class Foo(Base):子类必须重写父类中的抽象方法

      def 方法(self):

        pass

    一个类包含类抽象方法. 这个类一定是抽象类

    抽象类中可以有正常的方法

    抽象类中如果有抽象方法. 这个类将不能创建对象

    接口: 类中都是抽象方法

 1 # class Base:
 2 #     def login(self): #强制子类做xxx事情
 3 #         raise NotImplementedError('子类没有实现该方法') #报错抛异常
 4 # class A(Base):
 5 #     def login(self):
 6 #         print('1')
 7 # class B(Base):
 8 #     def login(self):
 9 #         print('1')
10 # class C(Base):
11 #     def denglu(self):
12 #         print('1')
13 #     # def login(self): #子类没有设置login函数 继承父类的login,父类的login报错
14 #     #     print('1')
15 # def login(c):
16 #     c.login()
17 # login(A())
18 # login(B())
19 # login(C())
20 # -----------------------
21 # from abc import ABCMeta,abstractmethod
22 # class Base(metaclass=ABCMeta): #抽象类
23 #     #抽象方法
24 #     @abstractmethod #
25 #     def login(self): #强制子类做xxx事
26 #         pass
27 #     def hehe(self):
28 #         print('123')
29 # # b = Base() #报错的原因是Base 是一个抽象类,含有抽象方法,不允许创建对象的
30 # 
31 # # 一个类如果全部都是抽象方法, 这个类可以被称为接口,用来约束子类和规范子类
32 # class Normal(Base):
33 #     def login(self):#重写了父类中的抽象方法
34 #         print('123')
35 # n = Normal()
36 # n.login()
37 
38 '''
39 当我们需要对子类进行约束:
40     1.抛出异常 NotImplementedError()  没有实现   -> 约定俗成.  多观察
41     2.写抽象类
42         from abc import ABCMeta, abstractmethod
43         class Base(metaclass = ABCMeta):
44             @abstractmethod
45             def 方法(self):
46                 pass
47         如果一个类中包含了抽象方法. 那么这个类一定是一个抽象类
48         一个抽象类中可以包含正常的方法
49 
50         接口: 接口中所有的方法都是抽象方法
51 
52         子类必须重写父类中的抽象方法. 否则子类也是一个抽象类
53 '''
View Code

二. 异常处理

  try:

    xxxx

  except Error as e :

  except....

  else:

  finally:

    收尾

  import traceback

  try:

    #尝试执行的代码

  except Exception as e:

    #除了错之后要做什么

    traceback.format_exc()  #获取堆栈信息(错误信息)

 1 # 异常处理
 2 # try:
 3 #     print(1/0)#  0不能做除数   ZeroDivisionError: division by zero
 4 # except ZeroDivisionError as e:
 5 #     print('0不能做除数')
 6 #我们通过try...except 可以把系统产生的这个错误获取到,过程叫捕获异常
 7 
 8 # 计算 a+b
 9 # import traceback
10 # def cul(a,b):
11 #     if (type(a) == int or type(a) ==float) and (type(b) == int or type(b) ==float):
12 #         return a+b
13 #     else:
14 #         # raise 抛出 Exception 错误和异常,所有错误的跟
15 #         raise Exception('我要的是数字')
16 #
17 # try:
18 #     print(cul(1, '2')) #加上异常处理
19 # except Exception as e :
20 #     #获取到错误信息, 我们需要访问堆栈信息
21 #     print(traceback.format_exc()) #获取堆栈信息
22 #     print('出现了错误')
23 
24 # 自定义异常
25 # class GenderException(Exception):
26 #     pass
27 # class Person:
28 #     def __init__(self,name,gender):
29 #         self.name = name
30 #         self.gender = gender
31 #     #洗澡 - > 男的进男浴室
32 #     def goto_nan_yushi(self):
33 #         if self.gender != '男':
34 #             raise GenderException('性别不对') #除了名字以外都是父类中的Exception
35 #         else :
36 #             print('欢迎光临')
37 # try:
38 #     p2 = Person('wusir','女')
39 #     p2.goto_nan_yushi()
40 # except GenderException as e :
41 #     print('你走错了')
42 # except Exception as e:
43 #     print('其他错误')
View Code

三. 日志

  logging

  critical

  error(最多)

  wraning

  info

  debug

 1 # import logging
 2 # # filename: ⽂件名
 3 # # format: 数据的格式化输出. 最终在⽇志⽂件中的样⼦
 4 # # 时间-名称-级别-模块: 错误信息
 5 # # datefmt: 时间的格式
 6 # # level: 错误的级别权重, 当错误的级别权重⼤于等于leval的时候才会写⼊⽂件
 7 # logging.basicConfig(filename='x1.log',
 8 #      format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
 9 #      datefmt='%Y-%m-%d %H:%M:%S',
10 # level=30)
11 # # 当前配置表示 0以上的分数会被写⼊⽂件
12 # # CRITICAL = 50
13 # # FATAL = CRITICAL
14 # # ERROR = 40
15 # # WARNING = 30
16 # # WARN = WARNING
17 # # INFO = 20
18 # # DEBUG = 10
19 # # NOTSET = 0
20 # logging.critical("我是critical") # 50分. 最贵的
21 # logging.error("我是error") # 40分
22 # logging.warning("我是warning")
23 # logging.info("我是info")
24 # logging.debug("我是debug")
25 # logging.log(1, "我什么都不是")
26 # #
27 # import traceback
28 # try:
29 #     print(1/0)
30 # except Exception:
31 #     logging.error(traceback.format_exc()) # 用法
32 #     print("出错了")
33 
34 
35 
36 # import logging
37 # # 创建⼀个操作⽇志的对象logger(依赖FileHandler)
38 # #                       open()
39 # file_handler = logging.FileHandler('zuo.log', 'a', encoding='utf-8')
40 # file_handler.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s"))
41 # logger1 = logging.Logger('qq', level=20)
42 # logger1.addHandler(file_handler) # 把文件助手和日志对象绑定
43 # logger1.error('我是A系统出错了') # 记录日志
44 #
45 #
46 # # 再创建⼀个操作⽇志的对象logger(依赖FileHandler)
47 # file_handler2 = logging.FileHandler('you.log', 'a', encoding='utf-8')
48 # file_handler2.setFormatter(logging.Formatter(fmt="%(asctime)s - %(name)s -%(levelname)s -%(module)s: %(message)s"))
49 # logger2 = logging.Logger('B系统', level=20)
50 # logger2.addHandler(file_handler2)
51 #
52 #
53 # import traceback
54 # try:
55 #     print(1/0)
56 # except Exception:
57 #     logger2.critical(traceback.format_exc())
58 #     print("出错了. 请联系管理员")
59 # print("程序继续知悉个")
60 
61 
62 
63 #
64 # from types import MethodType, FunctionType
65 # class Foo:
66 #     @classmethod
67 #     def func1(self):
68 #         pass
69 #     @staticmethod
70 #     def func2(self):
71 #         pass
72 #     def func3(self):
73 #         pass
74 #
75 #     def func4(self):
76 #         pass
77 #
78 # obj = Foo()
79 # lst.append(obj.func4)
80 # for item in lst:
81 #     print(isinstance(item, MethodType))
View Code
原文地址:https://www.cnblogs.com/Thui/p/9947076.html