繁体   English   中英

python抽象基类是否应该从object继承

[英]Should a python abstract base class inherit from object

关于abc的标准文档和我读过的其他教程都使用了定义抽象基类而不继承自object的示例。

class Foo(object):
    def __getitem__(self, index):
        ...
    def __len__(self):
        ...
    def get_iterator(self):
        return iter(self)

class MyIterable:
    __metaclass__ = ABCMeta

    @abstractmethod
    def __iter__(self):
        while False:
            yield None

在过去,我总是让我的类继承对象以具有新式类。 我应该和ABC一样吗?

声明的元类MyIterableABCMeta确保的实例MyIterable (或更适当地,的子类MyIterable ,因为它是一个抽象基类)将是“新”的风格。 如果您要创建一个MyIterable子类的实例,如下所示,它将表现为一个新的样式类。

class SubIterable(MyIterable):
    def __iter__(self):
        # your implementation here
        ...

>>> type(SubIterable())
<type '__main__'.MyIterable>

如果MyIterable确实是一个“旧”样式类,则type(SubIterable())将返回<type 'instance'> type(SubIterable()) <type 'instance'>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM