簡體   English   中英

防止在父構造函數中調用的方法在子構造函數中被調用

[英]Prevent a method that is called in the parent constructor from being called in the child constructor

假設我有一個父項 class 和一個從父項繼承的子項 class。

class Parent:
    def __init__(self)
    stubborn()

class Child():
      def __init__(self):
      super().__init__(self)

我不希望每次調用子 class 中的父構造函數時調用頑固方法。我該如何處理?

您可以定義一個Parentclassmethod來檢查您是否在Parent中,然后使用它來確定是否調用stubborn

class Parent:
    def __init__(self):
        if self.is_parent():
            self.stubborn()
    @classmethod
    def is_parent(cls):
        return cls is Parent
    def stubborn(self):
        print("stubborn called")

class Child(Parent): pass

p = Parent() # stubborn called
c = Child() # no output

如果不實際更改 function 或 stubgent stubborn() ) ,您將無法在parent.__init__()中對此做任何事情。

但是,作為孩子,您可以通過暫時將它變成一個存根來阻止stubborn()方法做任何重要的事情:

class Child():
    def __init__(self):
        old_stubborn = self.stubborn
        self.stubborn = lambda:None  # stub function that does nothing
        super().__init__(self)
        # put stubborn() back to normal
        self.stubborn = old_stubborn

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM