python - 跳过父类(super class) __init__ 的一部分?

标签 python inheritance

我有一个类是另一个类的子类。我想跳过一部分初始化过程,例如:

class Parent:
    __init__(self, a, b, c, ...):
        # part I want to keep:
        self.a = a
        self.b = b
        self.c = c
        ...
        # part I want to skip, which is memory and time consuming
        # but unnecessary for the subclass:
        self.Q = AnotherClass()

class Child(Parent):
    __init__(self):
        #a part of the parent initialization process, then other stuff

我想出的两个解决方案是:

  • Parent 类创建一个抽象类父类,该类不包含 Child 不需要的初始化部分,或者
  • 只复制我想要在 child 中初始化的 parent 的一部分

哪个最好,或者有更好的方法吗?

最佳答案

如何将 Q 的创建包装到私有(private)方法中,并在子类中覆盖该方法?

class Parent:
    def __init__(self, a, b, c, ...):
        # part I want to keep:
        self.a = a
        self.b = b
        self.c = c
        self._init_q()

    def _init_q():
        self.Q = AnotherClass()

class Child(Parent):
    def _init_q(self):
        pass  # do not init q when creating subclass

这不是最干净的方法,因为如果 Child 不需要 Q 要么它不应该是 Parent 的 child ,要么可能是 AnotherClass 放错了地方(也许它应该被注入(inject)到需要它的方法中)但它解决了您的问题而无需更改任何类接口(interface)。

关于python - 跳过父类(super class) __init__ 的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39558956/

相关文章:

python - 我有一个带有列表的 Pandas 专栏。对包含同一列中至少一个公共(public)元素的行进行分组

c++ - 为什么虚拟基类必须由最派生的类来构造?

Java - 错误 : return type is incompatible

ruby - Ruby 中的模块方法

python - 如何在python中分隔符的第一个实例上拆分字符串

python - 列表上的 re.sub - python 3

python - Python 中字符串的受限排列

python - 使用 Python networkx 从无向多图中删除循环

c++ - 类中静态成员的构造顺序

c++ - 是否可以在编译时检查类型是否派生自模板的某些实例化?