簡體   English   中英

PYTHON:如何讓孩子 class 從父級運行方法但基於不同的 if 條件?

[英]PYTHON: How to have a child class to run a method from parent but based on different if 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

無論如何將方法本身移動到父 class 但 if 條件具有各種通用 CONDITION 占位符? 這個占位符在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