Python:没有抽象方法的抽象类层次结构 [英] Python: hierarchy of abstract classes without abstract methods

查看:242
本文介绍了Python:没有抽象方法的抽象类层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,这是一个问题:


  1. 我想定义一个抽象类,比方说 AbstractA ,它不需要子类来实现其任何方法,而是扩展其功能。就将是接口类的Java而言。

  1. I want to define an abstract class, let's say AbstractA, which does not require subclasses to implement any of its methods, but rather to extend its functionality. In terms of Java that would be interface class.

此外,我希望能够创建一个抽象子类,例如 AbstractB AbstractA 中的具有相同的属性,但是有些方法重新定义或扩展了基类方法。

Moreover, I want to be able to create an abstract subclass, let's say AbstractB, of the AbstractA with the same properties, but some methods redefining or extending base class methods.

我不想创建类( AbstractA )抽象,例如通过检查 __ init__中的类名称, __ new __ ,因为这将需要抽象子类( AbstractB )来重新定义该方法及其主要功能,即构造或初始化新实例。或调用 super().__ init __(...)我也希望避免使用它(也许我在这里错了)。

I don't want though to make class (AbstractA) abstract e.g. through the check of class name in __init__ or __new__, because that would require abstract subclass (AbstractB) to redefine that method along with it's main functionality, i.e. construction or initialization of a new instance. Or to call super().__init__(...) which I'd prefer to avoid as well (maybe I'm wrong here).

所以,我想要这样的东西:

So, I want something like that:

class AbstractA:
    def __init__(self):
        # do initialization stuff

    def very_common_method(self, ...):
        # do very common stuff

class AbstractB(AbstractA):
    # do not duplicate initialization stuff here, inherit instead

    def less_common_method(self, ...):
        # do less common stuff

class AX(AbstractA):
    def specific_method_1(self, ...):

class BX(AbstractB):
    def specific_method_2(self, ...):

# Instantiating AbstractA or AbstractB should result in error.
# Instantiating AX or BX should not.

下面我有一个可能的解决方案。
我有什么缺点可以忽略吗?更好的解决方案?

Below I have a possible solution. Is there any disadvantages I overlook? Better solution?

谢谢!

推荐答案

以下是可能的解决方案:

Here's possible solution:

class AbstractA:
    _is_abstract = True

    def __init__(self):
        if self._is_abstract:
            raise RuntimeError("Abstract class instantiation.")
        # do initialization stuff

    def __init_subclass__(self):   # is called every time class is subclassed
        self._is_abstract = False  # thus makes sure abstract check fails on a subclass

class AbstractMixin:
    def __init_subclass__(self):
        self._is_abstract = True

class AbstractB(AbstractMixin, AbstractA):  # AbstractMixin takes precendence on MRO,
    # inherit __init__                      # so the class abstract check returns True.

    def __init_subclass__(self):
        self._is_abstract = False

class A(AbstractA):
    pass

class B(AbstractB):
    pass

AbstractA()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __init__
RuntimeError: Abstract class instantiation.

AbstractB()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __init__
RuntimeError: Abstract class instantiation.

A()
<__main__.A object at 0x7f0bba5112e8>

B()
<__main__.B object at 0x7f0bba511438>

这篇关于Python:没有抽象方法的抽象类层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆