抽象类:用来分离主体框架和局部实现,或将共用和定制解藕。从抽象类继承必须实现所有层级未被实现的抽象方法(被装饰器abstractmethod装饰的方法),否则无法创建实例。
定义抽象类,必须继承ABC,或使用ABCMeta类
from abc import ABC,ABCMeta, abstractmethod class A(metaclass=ABCMeta): # or class A(ABC): pass def __init__(self, name): self.name = name def save(self, data): with open(self.name, 'wb') as f: d = self.dump(data) f.write(d) def read(self): with open(self.name, 'rb') as f: return self.load(f.read()) @property # 先后顺序固定 @abstractmethod def dump(self, data): pass @abstractmethod def load(self, data): pass import pickle class B(A): def dump(self, data): return pickle.dumps(data) def load(self, data): return pickle.loads(data) b = B('aa.txt') b.save('hello world') print(b.read())