Mike的Python學院

OOP、軟體程式設計、程式語言、物件導向程式設計、Python、軟體開發、程式撰寫

Mike Ku

Learn Code With Mike品牌創辦人

2021/10/21

Python繼承(Inheritance)實用教學

Q:如何使用Python繼承?
將共同的屬性(Attribute)或方法(Method)定義在一個類別(Class)中,而其它類別(Class)則透過繼承(Inheritance)的方式來擁有它,如下範例:
class Transportation: # 交通工具
def __init__(self):
self.color = "white"
def drive(self): # 駕駛方法
print("drive method is called.")
class Car(Transportation):
def accelerate(self): # 加速方法
print("accelerate is method called.")
class Airplane(Transportation):
def fly(self): # 飛行方法
print("fly method is called.")
Transportation類別(Class)就叫父類別或基底類別(Base Class),而Car及Airplane類別(Class)就稱為子類別(Sub Class),在類別名稱的地方透過括號的方式來繼承(Inheritance),藉此擁有父類別公開的屬性(Attribute)及方法(Method),如下範例:
mazda = Car()
mazda.drive()
print(mazda.color)
Q:什麼是方法覆寫?
當子類別中定義了和父類別同名的方法(Method),這時候子類別的物件(Object)呼叫這個同名方法時,其中的實作內容將會覆蓋掉父類別的同名方法,這就叫做方法覆寫(Method Overriding),如下範例:
class Transportation: # 交通工具
def drive(self): # 駕駛方法
print("Base class drive method is called.")
class Car(Transportation):
def drive(self):
print("Sub class drive method is called.")
mazda = Car()
mazda.drive()
這時候如果我們想在子類別中執行父類別的方法(Method)時,則可以使用super()內建方法來達成,如下範例:
class Transportation: # 交通工具
def drive(self): # 駕駛方法
print("Base class drive method is called.")
class Car(Transportation):
def drive(self):
super().drive()
print("Sub class drive method is called.")
mazda = Car()
mazda.drive()
Q:什麼是多層繼承?
就是繼承(Inheritance)的層級超過一層以上,如下範例:
class Animal: # 動物類別
pass
class Bird(Animal):
def fly(self):
print("fly")
class Duck(Bird):
pass
duck = Duck()
duck.fly()
Q:什麼是多重繼承?
就是子類別繼承(Inheritance)一個以上的父類別,並且各類別應各司其職,避免有相同的方法,如下範例:
class Animal: # 動物類別
def eat(self):
print("Animal eat method is called.")
class Bird:
def walk(self):
print("Bird walk method is called.")
class Duck(Animal, Bird):
pass
duck = Duck()
duck.eat()
如果想要學習更多的Python應用教學,歡迎前往Learn Code With Mike( https://www.learncodewithmike.com/2020/01/python-inheritance.html )網站觀看更多精彩內容。
3 0 495 0