我對類繼承很陌生,需要一些幫助
我有一個問題,我想在從另一個繼承的父類方法呼叫后覆寫父類方法。
基本概念如下所示:
class Parent:
"""Parent class, that defines the logical workflow"""
def __init__(self):
pass
def outer_method(self):
# This method is called from the sub_classes
# everything in here is the same for all sub_classes
self.__inner_method(self)
def __inner_method(self):
# This method is called from self.outer_method()
# Everything in here will be handled differently by each sub_class
# And will therefore be overridden
pass
class Child(Parent):
"""Sub_class, that inherits from the Parent class"""
def __init__(self):
super().__init__()
def __inner_method(self):
# this should override Parent.__inner_method()
super().__inner_method()
print('Do some custom operations unique to this Sub_class')
這里的想法是,Child類呼叫outer_methodwhich 然后呼叫__inner_method,我想被子類覆寫。
但這不起作用。當我運行這個腳本時,
def main():
MyChild = Child()
MyChild.outer_method()
if __name__ == "__main__":
main()
發生的事情是,而不是呼叫Child.__inner_method(),Parent.__inner_method()被呼叫。
從繼承的外部方法呼叫后,如何讓子類覆寫父類的內部方法?
uj5u.com熱心網友回復:
問題的原因是您選擇的名稱,python 對類成員進行特殊處理,如果其名稱以該名稱開頭__但不以該名稱結尾,則呼叫name mangling,這樣做的原因是為了獲取私有變數的python 版本/methods,所以你__inner_method被重命名_Parent__inner_method為結果,任何__inner_method對父類的呼叫都會被修改為對這個重命名方法的呼叫,并且因為同樣的情況發生在子類上,它以_Child__inner_method它自己的一個結尾,這當然搞砸了如果不需要,可以使用繼承機制。
解決方法很簡單,全部重命名__inner_method為_inner_method.
_當您不想修改名稱時,單個是私有內容的約定,如果您愿意,__則當您希望它更加私密時......
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/325578.html
