跳过超类__init__的一部分?

时间:2016-09-18 14:49:43

标签: 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初始化的不需要部分,或
  • 仅复制我在子项中所需的父级初始化部分

哪种方法最好,还是有更好的方法?

1 个答案:

答案 0 :(得分:5)

如何将Q的创建包装到私有方法中,并在子类中重写该方法呢?

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,或者它不应该是父母的孩子,或者AnotherClass可能是错位的(也许它应该被注入需要它的方法)但它解决了你的问题而不改变任何类接口。

相关问题