是否可以在 Python 中创建抽象类? [英] Is it possible to make abstract classes in Python?

查看:28
本文介绍了是否可以在 Python 中创建抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I make a class or method abstract in Python?

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

I tried redefining __new__() like so:

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

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

but now if I create a class G that inherits from F like so:

class G(F):
    pass

然后我也不能实例化 G,因为它调用了它的超类的 __new__ 方法.

then I can't instantiate G either, since it calls its super class's __new__ method.

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

Is there a better way to define an abstract class?

推荐答案

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

Use the abc module to create abstract classes. Use the abstractmethod decorator to declare a method abstract, and declare a class abstract using one of three ways, depending upon your Python version.

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

In Python 3.4 and above, you can inherit from ABC. In earlier versions of Python, you need to specify your class's metaclass as ABCMeta. Specifying the metaclass has different syntax in Python 3 and Python 2. The three possibilities are shown below:

# 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

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

Whichever way you use, you won't be able to instantiate an abstract class that has abstract methods, but will be able to instantiate a subclass that provides concrete definitions of those methods:

>>> 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 中创建抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆