【问题标题】:Different behavior in base class __init__ depending on derived class基类 __init__ 中的不同行为取决于派生类
【发布时间】:2019-09-18 10:22:03
【问题描述】:

我有一个抽象类Base 包含一个成员布尔值do_thing,它将在启动时触发一次性操作,或者什么也不做。此变量可以被派生类Derived 覆盖,但在Derived 的__init__ 开头调用super().__init__() 会导致一次性操作始终基于do_thing 的设置到Base。

我只看到两个解决这个问题的选项,这对我来说似乎都不理想:

  1. 在每个派生类的__init__ 的末尾而不是开头调用super().__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

有没有我想念的更好的方法?

【问题讨论】:

  • 您可以将do_thing 设置为默认值为False 的kwarg,然后在派生类中显式传递True 值。
  • “在这里等待子类初始化”是什么意思? super().__init__() 在您设置 self.do_thing = True 之前运行祖先的课程 __init__ 以完成。
  • @JohnGordon 这就是我想不到的方式!如果这是一个答案,我会接受。谢谢
  • 我不希望在 Abstract 基类中有任何实现代码。

标签: python python-3.x abstract-class derived-class


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-10-11
      • 2017-08-26
      • 1970-01-01
      • 2013-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多