简体   繁体   English

PYTHON:如何让孩子 class 从父级运行方法但基于不同的 if 条件?

[英]PYTHON: How to have a child class to run a method from parent but based on different if conditions?

I have 2 child classes executing the same code but on different conditions.我有 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

Is there anyway to move the method itself to the parent class but with the if condition having a generic CONDITION placeholder of sorts?无论如何将方法本身移动到父 class 但 if 条件具有各种通用 CONDITION 占位符? And this placeholder is given its right value in the child class in the init ?这个占位符在init的子 class 中被赋予了正确的值?

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM