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()  #获取堆栈信息(错误信息)

  

四. 日志

  logging

  critical

  error(最多)

  wraning

  info

  debug

猜你喜欢

转载自www.cnblogs.com/Thui/p/9947076.html