繼承(1)

繼承

Posted by 劉啟仲 on Thursday, December 17, 2020

繼承 (Inheritance)

繼承(Inheritance):父類別跟子類別的階層關係,子類別會有父類別的屬性與方法。

在程式中將各類別共用屬性與方法方在一個獨立類別中,讓其他類別透過繼承方式來擁有這些屬性與方法,降低程式碼重複性

# parent class / base class
class Transportation:
    def __init__(self):
        self.exterior = "white"
    def drive(self):
        print("drive method is called.")
 
# child class / deroved class
class Car(Transportation):
    def move(self):
        print("move is method called.")
        
# child class / deroved class
class Airplane(Transportation):
    def fly(self):
        print("fly method is called.")
        
toyota = Car()
toyota.drive() # drive method is called.
print(toyota.exterior) # white

Override

子類別中定義了與父類別同樣名稱的方法,這時子類別在呼叫方法時,就會將其實作內容覆蓋掉父類別的方法

# parent class / base class
class Transportation:
    def __init__(self):
        self.exterior = "white"
    def drive(self):
        print("drive method is called.")
 
# child class / deroved class
class Car(Transportation):
    def move(self):
        print("move is method called.")
        
# child class / deroved class
class Airplane(Transportation):
    def __init__(self):
        self.exterior = "Red"
    def fly(self):
        print("fly method is called.")
        
evaair = Airplane()
evaair.drive() # drive method is called.
print(evaair.exterior) # Red

Super

如果想要在子類別中執行父類別方法,可以使用super( )。

# parent class / base class
class Transportation:
    def __init__(self):
        self.exterior = "white"
    def drive(self):
        print("drive method is called.")
 
# child class / deroved class
class Car(Transportation):
    def drive(self):
      	super().drive
        print("child class drive method is called.")
    def move(self):
        print("move is method called.")
        
# child class / deroved class
class Airplane(Transportation):
    def __init__(self):
        self.exterior = "Red"
    def fly(self):
        print("fly method is called.")
        
toyota = Car()
toyota.drive() 
# drive method is called.
# child class drive method is called.
print(toyota.exterior) # white