[英]Python overriden methods called from superclass
有很多關於 mangling 及其用法的信息,但是我很難理解以下代碼:
class Parent:
NAME = 'PARENT'
def __init__(self):
self.print_me()
def print_me(self):
print(f"Parent class {self.NAME}")
class Child(Parent):
NAME = 'CHILD'
def __init__(self):
super().__init__()
def print_me(self):
print(f"Child class {self.NAME}")
c = Child()
有人可以解釋一下如何從父 class init 調用覆蓋方法(print_me)並且不打印父 class PARENT 嗎? 如果我對NAME
和print_me
都使用修飾,則該方法不會被覆蓋,因此它是從預期的父級調用的。
Here the object(c) is child class object In child class the constructor calls the parent class and the parent class constructor calls the print_me method Here you called the child object so it will execute the child method. 如果 print_me 方法在 child 中不可用,那么它將執行 parent 方法
如果您需要它來打印父 function,則應改為創建父 object。
c = Parent()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.