是否可以在Python中创建抽象类?

发布于 2021-01-29 15:00:15

如何在Python中使类或方法抽象?

我尝试__new__()像这样重新定义:

class F:
    def __new__(cls):
        raise Exception("Unable to create an instance of abstract class %s" %cls)

但是现在,如果我创建一个像这样G继承的F类:

class G(F):
    pass

那么我也无法实例化G,因为它调用了其超类的__new__方法。

有没有更好的方法来定义抽象类?

关注者
0
被浏览
125
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    使用该abc模块创建抽象类。使用abstractmethod装饰器来声明方法摘要,并根据您的Python版本使用以下三种方式之一声明类摘要。

    在Python
    3.4及更高版本中,您可以从继承ABC。在Python的早期版本中,您需要将类的元类指定为ABCMeta。指定元类在Python
    3和Python 2中具有不同的语法。三种可能性如下所示:

    # Python 3.4+
    from abc import ABC, abstractmethod
    class Abstract(ABC):
        @abstractmethod
        def foo(self):
            pass
    
    
    
    # Python 3.0+
    from abc import ABCMeta, abstractmethod
    class Abstract(metaclass=ABCMeta):
        @abstractmethod
        def foo(self):
            pass
    
    
    
    # Python 2
    from abc import ABCMeta, abstractmethod
    class Abstract:
        __metaclass__ = ABCMeta
    
        @abstractmethod
        def foo(self):
            pass
    

    无论使用哪种方式,都将无法实例化具有抽象方法的抽象类,但将能够实例化提供这些方法的具体定义的子类:

    >>> Abstract()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: Can't instantiate abstract class Abstract with abstract methods foo
    >>> class StillAbstract(Abstract):
    ...     pass
    ... 
    >>> StillAbstract()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: Can't instantiate abstract class StillAbstract with abstract methods foo
    >>> class Concrete(Abstract):
    ...     def foo(self):
    ...         print('Hello, World')
    ... 
    >>> Concrete()
    <__main__.Concrete object at 0x7fc935d28898>
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看