from abc import ABCMeta, abstractmethod
class IStream(metaclass=ABCMeta):
@abstractmethod
def read(self, maxbytes=-1):
pass
@abstractmethod
def write(self, data):
pass
class SocketStream(IStream):
def read(self, maxbytes=-1):
pass
def write(self, data):
pass
def serialize(obj, stream):
if not isinstance(stream, IStream):
raise TypeError('Expected an IStream')
pass
if __name__ == "__main__":
a = SocketStream()
#IStream只能通过继承使用,不能直接实例化。
@abstractmethod 还能注解静态方法、类方法和 properties 。 但需要保证在方法的上的第一行:
class A(metaclass=ABCMeta):
@property
@abstractmethod
def name(self):
pass
@name.setter
@abstractmethod
def name(self, value):
pass
@classmethod
@abstractmethod
def method1(cls):
pass
@staticmethod
@abstractmethod
def method2():
pass
标准库中有很多用到抽象基类的地方。collections 模块定义了很多跟容器和迭代器(序列、映射、集合等)有关的抽象基类。 numbers 库定义了跟数字对象(整数、浮点数、有理数等)有关的基类。io 库定义了很多跟I/O操作相关的基类。
import collections
# Check if a is a sequence
if isinstance(a, collections.Sequence):
...
# Check if a is iterable
if isinstance(a, collections.Iterable):
...
# Check if a has a size
if isinstance(a, collections.Sized):
...
# Check if a is a mapping
if isinstance(a, collections.Mapping):