python @abstractmethod装饰器

塞巴斯蒂安:

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

这里

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

使用此装饰器要求该类的元类是ABCMeta或从其派生的。ABCMeta除非实例化了所有抽象方法和属性,否则无法实例化具有派生自其的元类的类

在这里

您可以将@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 必须实现抽象方法,但我也不例外。

备忘录:

您是否正在使用python3运行该代码?如果是的话,您应该知道在python 3中声明元类有更改,您应该这样做:

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 follwing two lines:
#   def abstractMethod(self):
#       return 0

c = ConcreteClass()
c.abstractMethod()

如果abstractMethod未为定义ConcreteClass,则在运行以上代码时将引发followin异常:TypeError: Can't instantiate abstract class ConcreteClass with abstract methods abstractMethod

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章