[英]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 中的父構造函數時調用頑固方法。我該如何處理?
您可以定義一個Parent
的classmethod
來檢查您是否在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.