【问题标题】:python @abstractmethod decoratorpython @abstractmethod 装饰器
【发布时间】:2011-11-04 00:18:45
【问题描述】:

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

来自here

abc.abstractmethod(function) 指示抽象方法的装饰器。

使用这个装饰器需要类的元类是ABCMeta 或 来源于它。具有从ABCMeta 派生的元类的类 除非它的所有抽象方法和 属性被覆盖。

还有here

您可以将@abstractmethod 装饰器应用于draw()等方法 必须执行;然后 Python 将引发异常 没有定义方法的类。请注意,该例外仅 当您实际尝试创建子类的实例时引发 缺少方法。

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

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 必须实现抽象方法,但我没有例外。

【问题讨论】:

  • 哪个 Python?它报告错误对我来说很好。此外,您始终可以引发 NotImplementedError 而不是使用abc
  • 我在 mouad 答案上发表了评论,来自python 的链接默认设置为python3。我会记住提出异常,因为在 python 上编写具有这些更改的可移植代码似乎与我的 python 知识相去甚远。

标签: python abc abstract-methods


【解决方案1】:

abc 导入ABC 并使您自己的抽象类成为ABC 的子类可以帮助使代码看起来更简洁。

from abc import ABC, abstractmethod

class AbstractClass(ABC):

  @abstractmethod
  def abstractMethod(self):
    return

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

# The following would raise the TypeError complaining abstracteMethod is not impliemented
c = ConcreteClass()  

使用 Python 3.6 测试

【讨论】:

    【解决方案2】:

    您是否使用 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()
    

    如果abstractMethod没有为ConcreteClass定义abstractMethod,运行上述代码时会抛出如下异常:TypeError: Can't instantiate abstract class ConcreteClass with abstract methods abstractMethod

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 2014-01-23
    • 1970-01-01
    • 2021-05-20
    • 2020-02-10
    • 2011-04-28
    相关资源
    最近更新 更多