基本方法重寫
以下是 Python 中基本覆蓋的示例(為了清晰和相容 Python 2 和 3,使用新樣式類和 print 與 ()):
class Parent(object):
def introduce(self):
print("Hello!")
def print_name(self):
print("Parent")
class Child(Parent):
def print_name(self):
print("Child")
p = Parent()
c = Child()
p.introduce()
p.print_name()
c.introduce()
c.print_name()
$ python basic_override.py
Hello!
Parent
Hello!
Child
建立 Child 類時,它繼承了 Parent 類的方法。這意味著父類具有的任何方法,子類也將具有。在示例中,introduce 是為 Child 類定義的,因為它是為 Parent 定義的,儘管沒有在 Child 的類定義中明確定義。
在此示例中,當 Child 定義其自己的 print_name 方法時,將發生覆蓋。如果沒有宣告這個方法,那麼 c.print_name() 會列印 Parent。然而,Child 已經覆蓋了 Parent 對 print_name 的定義,所以現在在呼叫 c.print_name() 時,會列印出 Child 這個詞。