接口继承:
基类不用实现内部逻辑,只是为了规范子类,可以用abc模块中以添加装饰器的方式实现
import abc
class All_file(metaclass=abc.ABCMeta): @abc.abstractmethod
def read(self):
pass @abc.abstractmethod
def write(self):
pass class Disk(All_file):
def read(self):
print("Disk read")
def write(self):
pass
class Cdrom(All_file):
def read(self):
pass
def write(self):
pass m1 = Disk()
m1.read()
m1.write()
在子类中调用父类方法:
class Vehiale:
country = "China"
def __init__(self,name,speed,load,power):
self.name = name
self.speed = speed
self.load = load
self.power = power def run(self):
print("kaidongla") class Subway(Vehiale):
def __init__(self,name,speed,load,power,line):
Vehiale.__init__(self,name,speed,load,power)
self.line = line
def show_info(self):
print(self.speed,self.line,self.load,self.name,self.power)
def run(self):
Vehiale.run(self)
print("%s %s 线,开动啦" %(self.name,self.line)) line13=Subway("100m/s",13,1000,"北京地铁","电")
line13.show_info()
line13.run()
多态:
不同的实例可以去调用同一个方法,但实现的效果不同。
class H2O:
def __init__(self,name,temperature):
self.name = name
self.temperature = temperature
def turn_ice(self):
if self.temperature < 0:
print('[%s]温度太低结冰了'%self.name)
elif self.temperature > 0 and self.temperature < 100:
print('[%s]液化成水'%self.name)
elif self.temperature>100:
print('[%s]温度太高变成水蒸气了'%self.name) class Water(H2O):
pass
class Ice(H2O):
pass
class Steam(H2O):
pass w1 = Water('水',25)
i1 = Ice('冰',-20)
s1 = Steam('蒸汽',300) # w1.turn_ice()
# i1.turn_ice()
# s1.turn_ice()
#多态反映的是一种运行时候的状态
def func(obj):
obj.turn_ice() func(w1)
func(i1)
func(s1)