我对ABC寄存器方法感到困惑。
下面的代码:
import io
from abc import ABCMeta, abstractmethod
class IStream(metaclass=ABCMeta):
@abstractmethod
def read(self, maxbytes=-1):
pass
@abstractmethod
def write(self, data):
pass
IStream.register(io.IOBase)
f = open('foo.txt')
isinstance(f, Istream) # returns true
当你注册io.IOBase的时候,到底发生了什么?你是说IOBase类只能有Istream ABC类定义的方法吗?ABC注册其他类的好处是什么?
2条答案
按热度按时间bvpmtnay1#
它只是让
issubclass(io.IOBase, IStream)
返回True
(这意味着io.IOBase
的一个示例是IStream
的一个示例),由注册该类的程序员来确保io.IOBase
实际上 * 符合 *IStream
定义的API。原因是让你定义一个
IStream
形式的接口,并让你指出一个可能实际上没有从IStream
继承的类满足这个接口。本质上,它只是形式化的duck类型。toe950272#
例如,我们可以替换**
Cat
类扩展Animal
类**如下:以下代码具有register():
然后,上面的两个代码都输出以下相同的结果,显示**
Cat
class是Animal
class**的子类: