【问题标题】:Abstract base class is not enforcing function implementation抽象基类不强制执行函数
【发布时间】:2015-07-03 08:05:53
【问题描述】:
from abc import abstractmethod, ABCMeta

class AbstractBase(object):
  __metaclass__ = ABCMeta

  @abstractmethod
  def must_implement_this_method(self):
      raise NotImplementedError()

class ConcreteClass(AbstractBase):

   def extra_function(self):
       print('hello')

   # def must_implement_this_method(self):
     # print("Concrete implementation")


d = ConcreteClass()  # no error
d.extra_function()

我使用的是 Python 3.4。我想定义一个抽象基类,它定义了一些需要由它的子类实现的函数。但是当子类没有实现函数时,Python 不会引发 NotImplementedError...

【问题讨论】:

  • 拨打d.must_implement_this_method()会发生什么?

标签: python python-3.x abstract-class python-3.4


【解决方案1】:

元类声明的语法在 Python 3 中发生了变化Python 3 在 基类列表中使用 关键字参数,而不是 __metaclass__ 字段:

import abc

class AbstractBase(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def must_implement_this_method(self):
        raise NotImplementedError()

现在调用d = ConcreteClass()引发异常因为从ABCMeta 派生的元类无法实例化,除非其所有抽象方法和属性被覆盖(更多信息参见@abc.abstractmethod):

TypeError: Can't instantiate abstract class ConcreteClass with abstract methods
must_implement_this_method

希望这会有所帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 2010-11-26
    • 2015-09-14
    • 2017-11-27
    • 2019-10-13
    • 2010-12-12
    相关资源
    最近更新 更多