python之接口继承
接口继承
接口继承就是(基类)父类定义好2个函数属性(接口),所有的子类必须有这2个函数属性,缺一不可,不是说省代码的,是用来做强制性约束的
基类里面的方法不用具体的实现,只是一个规范而已
1.1实现一个一切皆文件的概念
class Disk:
def read(self):
pass
def write(self):
pass
class Cdrom:
def read(self):
pass
def write(self):
pass
class Mem:
def read(self):
pass
def write(self):
pass
1.2可以定义一个基类,对上面代码进行改进
class Allfile:
def read(self):
pass
def write(self):
pass
class Disk(Allfile):
def read(self):
print("disk read")
def write(self):
print("disk write")
class Cdrom(Allfile):
def read(self):
print("cdrom read")
def write(self):
print("cdrom write")
class Mem(Allfile):
def read(self):
print("mem read")
def write(self):
print("mem write")
1.3但是子类也可以不按照你规定的出牌,Mem就是不听话,他不定义write的函数属性,然后就会从父类找。父类里面又是pass
class Allfile:
def read(self):
pass
def write(self):
pass
class Disk(Allfile):
def read(self):
print("disk read")
def write(self):
print("disk write")
class Cdrom(Allfile):
def read(self):
print("cdrom read")
def write(self):
print("cdrom write")
class Mem(Allfile):
def read(self):
print("mem read")
m1=Mem()
m1.read()
m1.write()
C:\python35\python3.exe D:/pyproject/day25/接口继承.py
mem read
1.4所以python就有一个专门的模块来实现这个强制性的约束子类,模块叫abc
导入模块abc,给父类2个属性加上装饰器之后,如果子类再少属性的话,就直接报错了,这样就强制性的约束了子类必须有父类的2个方法了
import abc
class Allfile(metaclass=abc.ABCMeta):
@abc.abstractstaticmethod
def read(self):
pass
@abc.abstractstaticmethod
def write(self):
pass
class Disk(Allfile):
def read(self):
print("disk read")
def write(self):
print("disk write")
class Cdrom(Allfile):
def read(self):
print("cdrom read")
def write(self):
print("cdrom write")
class Mem(Allfile):
def read(self):
print("mem read")
m1=Mem()
TypeError: Can't instantiate abstract class Mem with abstract methods write
1.5当子类Mem也加上write这个方法之后就可以正常运行了
import abc
class Allfile(metaclass=abc.ABCMeta):
@abc.abstractstaticmethod
def read(self):
pass
@abc.abstractstaticmethod
def write(self):
pass
class Disk(Allfile):
def read(self):
print("disk read")
def write(self):
print("disk write")
class Cdrom(Allfile):
def read(self):
print("cdrom read")
def write(self):
print("cdrom write")
class Mem(Allfile):
def read(self):
print("mem read")
def write(self):
print("mem write")
m1=Mem()
m1.read()
m1.write()
mem read
mem write