我有一个类是另一个类的子类。我想跳过一部分初始化过程,例如:
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/