我有一个抽象类Base
,其中包含一个成员boolean do_thing
,它将在启动时触发一次性操作,或者什么都不做。这个变量可以被派生类Derived
覆盖,但是在super().__init__()
的Derived
开头做一个__init__
调用导致一次性动作总是基于do_thing
设置的Base
。
我只看到两种解决这个问题的方法,对我来说似乎都不合适:
super().__init__()
末尾调用__init__
而不是开头,这意味着我不能依赖于Base
中设置的其他默认变量。__init__
末尾显式调用一次性操作,这意味着重复的代码,或Base
中的一个额外的函数,它只会在启动时被调用。一些示例代码
from abc import ABC
class Base(ABC):
def __init__(self):
self.do_thing = False
# Want to wait for child class init before running this
if self.do_thing:
configuration.set(do_thing_parameters)
class Derived(Base):
def __init__(self):
super().__init__()
# Should have configs properly set based on this being true
self.do_thing = True
class RegularDerived(Base):
def __init__(self):
super().__init__()
# Don't modify the config
有没有更好的办法让我失踪?
尝试将“do_thing”变量设置为默认参数,如下所示......
from abc import ABC
class Base(ABC):
def __init__(self, do_thing=False):
if do_thing:
configuration.set(do_thing_parameters)
class Derived(Base):
def __init__(self):
super().__init__(True)
根据您的描述,听起来您的do_thing
功能与您的课程有关,而不是您的实例。如果是这样的话,将它作为__init__
的参数似乎是不对的。你还有其他选择,我会选择
一个类属性
class Base:
_do_thing = False
def __init__(self):
if self._do_thing:
configuration.set(do_thing_parameters)
class Derived(Base):
_do_thing = True
class RegularDerived(Base):
pass
那你甚至不需要在子类中定义__init__