python @abstractmethod 装饰器

标签 python abc abstract-methods

我已阅读有关抽象基类的 python 文档:

来自 here :

abc.abstractmethod(function) A decorator indicating abstract methods.

Using this decorator requires that the class’s metaclass is ABCMeta or is derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden.

还有 here

You can apply the @abstractmethod decorator to methods such as draw() that must be implemented; Python will then raise an exception for classes that don’t define the method. Note that the exception is only raised when you actually try to create an instance of a subclass lacking the method.

我已经使用此代码进行了测试:

import abc

class AbstractClass(object):
  __metaclass__ = abc.ABCMeta

  @abc.abstractmethod
  def abstractMethod(self):
    return

class ConcreteClass(AbstractClass):
  def __init__(self):
    self.me = "me"

c = ConcreteClass()
c.abstractMethod()

代码运行良好,所以我不明白。如果我输入 c.abstractMethod 我得到:

<bound method ConcreteClass.abstractMethod of <__main__.ConcreteClass object at 0x7f694da1c3d0>>

我在这里缺少什么? ConcreteClass 必须实现抽象方法,我也不异常(exception)。

最佳答案

您是否使用 python3 来运行该代码?如果是,你应该知道在 python3 中声明元类 have changes你应该这样做:

import abc

class AbstractClass(metaclass=abc.ABCMeta):

  @abc.abstractmethod
  def abstractMethod(self):
      return

完整的代码和答案背后的解释是:

import abc

class AbstractClass(metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def abstractMethod(self):
        return

class ConcreteClass(AbstractClass):

    def __init__(self):
        self.me = "me"

# Will get a TypeError without the following two lines:
#   def abstractMethod(self):
#       return 0

c = ConcreteClass()
c.abstractMethod()

如果没有为ConcreteClass定义abstractMethod,运行上述代码时会引发如下异常:TypeError: Can't instantiate abstract class ConcreteClass with抽象方法 abstractMethod

关于python @abstractmethod 装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7196376/

相关文章:

python - Pyramid : session 和静态 Assets

python - 在mean()之后绘图

python - 如何使用 exchangelib 获取非收件箱文件夹的邮件

go - 没有主体的功能是什么意思?

java - 当没有实现时,抽象方法如何工作?

scala - scala 编译器可以在混合时强制实现抽象特征方法吗?

python - 使用 Matplotlib 进行 3D 绘图时 cmath 的问题

Python 集合.MappingView

python - 将 Singleton 实现为元类,但用于抽象类

python - 使用从 json 键定义的抽象方法创建 ABC