接口继承
接口继承就是(基类)父类定义好函数属性(接口),所有的子类必须有这些定义好的函数属性,缺一不可。不是为了省代码的,是用来做强制性约束的
举例说明如下:
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
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")
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() # 输出mem read
m1.write() # 没有输出
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
学习了:)