今天練習的是class(類)的繼承.
有三種. 隱式繼承, 顯式覆蓋, 在運行前/後替換
用Notepad++打下列的程式碼,
另存為ex44.py. 我附上中文注釋方便好讀.
# 定義一個類叫Parent
class Parent(object):
# 定義一個函數叫override, 並列印出下面那一行字.
def override(self):
print("PARENT override()")
# 定義一個函數叫implicit, 並列印出下面那一行字.
def implicit(self):
print("PARENT implicit()")
# 定義一個函數叫altered, 並列印出下面那一行字.
def altered(self):
print("PARENT altered()")
# 定義一個類叫Child, 並繼承父類(Parent)的行為
class Child(Parent):
# 定義一個函數叫override, 並列印出下面那一行字.
def override(self):
print("CHILD override()")
# 定義一個函數叫altered, 並列印出下面那一行字.
def altered(self):
print("CHILD, BRFORE PARENT altered()")
# super可以調用父類
super(Child, self).altered()
print("CHILD AFTER PARENT altered()")
dad = Parent()
son = Child()
# 這裡的son.implicit會隱式繼承父類的implicit函數
dad.implicit()
son.implicit()
# 這裡的son.override會顯式覆蓋父類的override函數
dad.override()
son.override()
# 這裡的son.altered會運行前/後替換父類的altered函數
dad.altered()
son.altered()
然後用Windows的cmd, 執行python.
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\LP3THW C:\Users\Peter\Desktop\Python\LP3THW>python ex44.py PARENT implicit() PARENT implicit() PARENT override() CHILD override() PARENT altered() CHILD, BRFORE PARENT altered() PARENT altered() CHILD AFTER PARENT altered() C:\Users\Peter\Desktop\Python\LP3THW>
完成
最初發表 / 最後更新: 2018.10.02 / 2018.10.02

0 comments:
張貼留言