接口继承:

基类不用实现内部逻辑,只是为了规范子类,可以用abc模块中以添加装饰器的方式实现

 1 import abc
 2 class All_file(metaclass=abc.ABCMeta):
 3 
 4     @abc.abstractmethod
 5     def read(self):
 6         pass
 7 
 8     @abc.abstractmethod
 9     def write(self):
10         pass
11 
12 class Disk(All_file):
13     def read(self):
14         print("Disk read")
15     def write(self):
16         pass
17 class Cdrom(All_file):
18     def read(self):
19         pass
20     def write(self):
21         pass
22 
23 m1 = Disk()
24 m1.read()
25 m1.write()
View Code

在子类中调用父类方法:

 1 class Vehiale:
 2     country = "China"
 3     def __init__(self,name,speed,load,power):
 4         self.name = name
 5         self.speed = speed
 6         self.load = load
 7         self.power = power
 8 
 9     def run(self):
10         print("kaidongla")
11 
12 class Subway(Vehiale):
13     def __init__(self,name,speed,load,power,line):
14         Vehiale.__init__(self,name,speed,load,power)
15         self.line = line
16     def show_info(self):
17         print(self.speed,self.line,self.load,self.name,self.power)
18     def run(self):
19         Vehiale.run(self)
20         print("%s %s 线,开动啦" %(self.name,self.line))
21 
22 line13=Subway("100m/s",13,1000,"北京地铁","")
23 line13.show_info()
24 line13.run()
View Code

多态:

不同的实例可以去调用同一个方法,但实现的效果不同。

 1 class H2O:
 2     def __init__(self,name,temperature):
 3         self.name = name
 4         self.temperature = temperature
 5     def turn_ice(self):
 6         if self.temperature < 0:
 7             print('[%s]温度太低结冰了'%self.name)
 8         elif self.temperature > 0 and self.temperature < 100:
 9             print('[%s]液化成水'%self.name)
10         elif self.temperature>100:
11             print('[%s]温度太高变成水蒸气了'%self.name)
12 
13 class Water(H2O):
14     pass
15 class Ice(H2O):
16     pass
17 class Steam(H2O):
18     pass
19 
20 
21 
22 w1 = Water('',25)
23 i1 = Ice('',-20)
24 s1 = Steam('蒸汽',300)
25 
26 # w1.turn_ice()
27 # i1.turn_ice()
28 # s1.turn_ice()
29 #多态反映的是一种运行时候的状态
30 def func(obj):
31     obj.turn_ice()
32 
33 func(w1)
34 func(i1)
35 func(s1)
View Code

 

Copyright © 2024 喜气洋洋的破罐破摔
Powered by .NET 9.0 on Kubernetes