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

标签 python class inheritance abstract-class abstract

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

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

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

但现在如果我创建一个继承自 F 的类 G,如下所示:

class G(F):
    pass

那么我也不能实例化 G,因为它调用了它的父类(super class)的 __new__ 方法。

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

最佳答案

使用 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>

关于python - 是否可以在 Python 中创建抽象类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13646245/

相关文章:

python - 使用 itertools 的排列爆炸内存

python - 将 API 更改为许多实用程序类

python - 使用 subprocess.Popen() 打开程序时出错

c# - 在与父类 ID 不同的子类(继承)上添加 PK

c++ - 有条件的虚拟继承和对虚拟基成员的访问

python - 提取最后一次出现的大括号之间的文本

javascript - 如何将javascript类构造函数参数动态映射到实例属性

python - "The set of methods, however, is fixed when the class is first defined"是真的吗?

class - 为什么 ifelse 将 data.frame 转换为列表 : ifelse(TRUE, data.frame(1), 0)) != data.frame(1)?

c++ - 构造函数调用虚函数的困惑