Python中的抽象方法继承

And*_*rea 5 python inheritance abc abstract

假设我们有一个 Python 类,它使用abc模块来定义一个抽象属性:

import abc

class A(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractproperty
    def test_attribute(self):
        raise NotImplementedError
Run Code Online (Sandbox Code Playgroud)

现在让我们考虑通过添加新方法 ( )B来定义子类,并通过实现最初在 中声明的抽象方法来定义子类:Atest_method()CBA

class B(A):

    def test_method(self):
        pass

class C(B):

    def test_attribute(self):
        # Implement abstract attribute
        pass
Run Code Online (Sandbox Code Playgroud)

假设我想保持B抽象(不可实例化),我是否应该test_attribute在 中重新定义抽象属性 ( ) 和元类赋值B?或者继承它们就足够了A(如上面的代码)?

我知道Python允许我不重新定义抽象方法,从而从父类继承它们。从理论软件工程的角度来看,这是正确的吗?

我这么问是因为如果我没记错的话,其他语言(例如Java)不允许继承抽象方法而不将它们重新实现为抽象......

mgi*_*son 5

您几乎已经获得了所有代码,您可以随时测试它并查看它是否有效...但是作为剧透,您的设计只要C.test_attributeproperty.

如果您尝试创建 的实例B,那么您会遇到问题,因为尚未创建整个抽象接口,但是可以将其创建为C(以及稍后可能的其他类...)的基类。

例如:

import abc

class A(object):
  __metaclass__ = abc.ABCMeta

  @abc.abstractproperty
  def foo(self):
    pass

class B(A):
  def bar(self):
    return "bar"

class C(B):
  @property
  def foo(self):
    return "foo"

print C().foo    # foo
print C().bar()  # bar
print B().foo    # TypeError
Run Code Online (Sandbox Code Playgroud)