|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
##问题
你想定义一个接口或抽象类,并且通过执行类型检查来确保子类实现了某些特定的方法,类似于Java的接口。
##解决方案
使用 abc 模块可以很轻松的定义抽象基类:
- from abc import ABCMeta, abstractmethod
- class IStream(metaclass=ABCMeta):
- @abstractmethod
- def read(self, maxbytes=-1):
- pass
- @abstractmethod
- def write(self, data):
- pass
复制代码
抽象类的一个特点是它不能直接被实例化,比如你想像下面这样做是不行的:
- >>> from module_abc import IStream
- >>> a = IStream()
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: Can't instantiate abstract class IStream with abstract methods read, write
- >>>
复制代码
抽象类的目的就是让别的类继承它并实现特定的抽象方法:
- from abc import ABCMeta, abstractmethod
- class IStream(metaclass=ABCMeta):
- @abstractmethod
- def read(self, maxbytes=-1):
- pass
- @abstractmethod
- def write(self, data):
- pass
- # a = IStream() # TypeError: Can't instantiate abstract class IStream with abstract methods read, write
- class SocketStream(IStream):
- def read(self, maxbytes=-1):
- pass
- def write(self, data):
- pass
复制代码
- 参考文章:https://python3-cookbook.readthedocs.io/zh_CN/latest/c08/p12_define_interface_or_abstract_base_class.htmlhttps://docs.python.org/zh-cn/3/library/abc.html |
|