基类__init__中的不同行为取决于派生类

问题描述 投票:0回答:2

我有一个抽象类Base,其中包含一个成员boolean do_thing,它将在启动时触发一次性操作,或者什么都不做。这个变量可以被派生类Derived覆盖,但是在super().__init__()Derived开头做一个__init__调用导致一次性动作总是基于do_thing设置的Base

我只看到两种解决这个问题的方法,对我来说似乎都不合适:

  1. 在每个派生类的super().__init__()末尾调用__init__而不是开头,这意味着我不能依赖于Base中设置的其他默认变量。
  2. 在每个派生类的__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

有没有更好的办法让我失踪?

python python-3.x abstract-class derived-class
2个回答
0
投票

尝试将“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)

1
投票

根据您的描述,听起来您的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__

© www.soinside.com 2019 - 2024. All rights reserved.