【问题标题】:PYTHON: How to have a child class to run a method from parent but based on different if conditions?PYTHON:如何让子类从父类运行方法但基于不同的 if 条件?
【发布时间】:2022-01-13 16:53:52
【问题描述】:

我有 2 个子类在不同的条件下执行相同的代码。

class Child1(Parent):
  ...
  def updateChart(self):
    if self.value % 15 == 0:
      self.value += 5

class Child2(Parent):
  ...
  def updateChart(self):
    if self.value % 30 == 0:
      self.value += 5

有没有办法将方法本身移动到父类,但 if 条件有一个通用的 CONDITION 占位符?并且这个占位符在 init 的子类中被赋予了正确的值?

【问题讨论】:

  • 使用def condition(self): ... 方法,然后只使用if self.condition(): self.value += 5
  • 或者甚至只是一个用作模数的属性:if self.value % self.m == 0:。方法更容易作为抽象方法添加到父级,但如果子级忽略提供一个默认模数,则父级可能会提供一个默认模数。

标签: python class inheritance attributes


【解决方案1】:
class Parent:
    def __init__(self, mod):
        self.mod = mod
        self.value = 0

    def updateChart(self):
        print(f"{type(self)} before update self.value={self.value} (mod={self.mod})")
        if (self.value % self.mod) == 0:
            self.value += 5
            print(f"{type(self)} updated self.value={self.value} (mod={self.mod})")
        else:
            # print(f"{type(self)} no update ({self.value} % {self.mod} != 0)")
            pass

class Child1(Parent):
  def __init__(self):
      super().__init__(mod=15)

class Child2(Parent):
  def __init__(self):
      super().__init__(mod=30)

for i in range(0, 61, 5):
    c1 = Child1()
    c1.value = i
    c1.updateChart()

    c2 = Child2()
    c2.value = i
    c2.updateChart()

【讨论】:

    猜你喜欢
    • 2018-04-24
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2014-09-23
    • 2015-04-08
    • 2022-07-20
    相关资源
    最近更新 更多