【发布时间】:2019-09-18 10:22:03
【问题描述】:
我有一个抽象类Base 包含一个成员布尔值do_thing,它将在启动时触发一次性操作,或者什么也不做。此变量可以被派生类Derived 覆盖,但在Derived 的__init__ 开头调用super().__init__() 会导致一次性操作始终基于do_thing 的设置到Base。
我只看到两个解决这个问题的选项,这对我来说似乎都不理想:
在每个派生类的
__init__的末尾而不是开头调用super().__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设置为默认值为False 的kwarg,然后在派生类中显式传递True值。 -
“在这里等待子类初始化”是什么意思?
super().__init__()在您设置self.do_thing = True之前运行祖先的课程__init__以完成。 -
@JohnGordon 这就是我想不到的方式!如果这是一个答案,我会接受。谢谢
-
我不希望在 Abstract 基类中有任何实现代码。
标签: python python-3.x abstract-class derived-class