标签:meta 强制 rom 不用 导入 文件的 ror str 导入模块
接口继承就是(基类)父类定义好2个函数属性(接口),所有的子类必须有这2个函数属性,缺一不可,不是说省代码的,是用来做强制性约束的
基类里面的方法不用具体的实现,只是一个规范而已
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
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")
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
导入模块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
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
标签:meta 强制 rom 不用 导入 文件的 ror str 导入模块
原文地址:https://www.cnblogs.com/NumerOne/p/11465127.html