简体   繁体   中英

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.

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? And this placeholder is given its right value in the child class in the init ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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