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

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

问题描述

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

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

我尝试重新定义 __ new __()因此:

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

但现在如果我创建一个类 G ,继承自 F

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 装饰器声明

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






$ b

# 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天全站免登陆