1. 写一个父类. 父类中的某个方法要抛出一个异常 NotImplementedError (重点)
2. 抽象类和抽象方法
from abc import ABCMeta, abstractmethod
class Base(metaclass = ABCMeta):
@abstractmethod
def fangfa(self):
pass
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
# class Base: # # 对子类惊醒了约束,必须重写该方法 # # 以后上班了拿刀公司代码之后 发现了NotImplementedError 继承他 直接重写他 # def login(self): # raise NotImplementedError('重写login这个方法,否则报错') # # class Putong(Base): # def login(self): # print('普通人登录') # # class BaWu(Base): # def login(self): # print('吧务登录') # # class GuanLi(Base): # def login(self): # def denglu(self) 报错 , 上层程序员写代码没有按照规范来 # print('管理登录') # # # 对登录功能的整合 # def func(cl): # cl.login() # # m = Putong() # b = BaWu() # gl = GuanLi() # # func(m) # func(b) # func(gl) # 抽象 # 抽象方法不需要给出具体的方法体,抽象方法内只写一个pass就可以了 # 在一个类中如果有一个方法是抽象方法,那么这个类一定是一个抽象类 # 抽象类中,如果有抽象方法,此时这个类不能创建对象 # 如果一个类中所有的方法都是抽象方法,这个类可以被称为接口类 # 写一个抽象方法: 导入一个模块 from abc import ABCMeta, abstractmethod # 此时抽象类不能创建对象 class Animal(metaclass = ABCMeta): # 写完这个东西,就是个抽象类 @abstractmethod def chi( self ): pass # 吃应该只是一个抽象概念,没办法完美的描述出来吃什么东西 # 抽象类中可以有正常的方法 def dong( self ): print ( '动物会动' ) # class Cat(Animal): # 此时猫里面也有一个抽象方法, 此时的猫是创建不了对象的 # pass class Cat(Animal): def chi( self ): # 重写父类中的抽象方法 print ( '猫喜欢吃鱼' ) a = Cat() a.chi() a.dong() |