[python] 使用 super() 來繼承類別

Visits: 0

類別( Class)的繼承

在 python 中,創建了一個父類別後,我若想要在父類別底下新增子類別,可以直接透過繼承的方式,將父類別有的屬性繼承下來,且子類別中我可以另外創建屬性而不影響父類別。

先創建父類別 Robot

class Robot():
    def __init__(self, name, color, weight):  # constracter
        self.name = name
        self.color = color
        self.weight = weight

    def introduceSelf(self):
        print("My name is: ", self.name, ", color is: ", self.color, ", weight is: ", self.weight)

# init the class
r1 = Robot("Tom", "red", 30)
r2 = Robot("Jerry", "blue", 40)
r1.introduceSelf()
r2.introduceSelf()

執行結果為

My name is:  Tom , color is:  red , weight is:  30
My name is:  Jerry , color is:  blue , weight is:  40

創建繼承自 Robot 的子類別 MicroRobot

我想要在 Robot 底下,再新增一個子類別叫做 MicroRobot ,這個子類別具有 Robot 的所有屬性與新的屬性 dev_lang (這個機器使用的開發語言)。

class MicroRobot(Robot):  # 繼承自 Robot
    def __init__(self, name, color, weight, dev_lang):
        super().__init__(name, color, weight)  # 透過 super() 來繼承 Robot 的屬性
        self.dev_lang = dev_lang

    def introduceSelf(self):
        print("My name is: ", self.name, ", color is: ", self.color, ", weight is: ", self.weight)
        print("I was developed by: ", self.dev_lang)

# init the class
r1 = MicroRobot("Tom", "red", 30, "python")
r2 = MicroRobot("Jerry", "blue", 40, "java")
r1.introduceSelf()
r2.introduceSelf()
My name is:  Tom , color is:  red , weight is:  30
I was developed by:  python
My name is:  Jerry , color is:  blue , weight is:  40
I was developed by:  java

透過 super() ,可以把父類別的屬性繼承到子類別,在子類別中,可以再另外開發專屬於子類別的屬性、方法…等,讓程式的功能分離,也更乾淨更好維護。

介紹一些檢查類別 (Class) 的方法

  • help() : 可以印出類別所具有的屬性、方法以及繼承來源,執行 print(help(MicroRobot)) 後,下面結果可讀出的訊息為: MicroRobot 是繼承自 Robot 以及具有的屬性
Help on class MicroRobot in module __main__:

class MicroRobot(Robot)
 |  Method resolution order:
 |      MicroRobot
 |      Robot
 |      builtins.object
 |  
 |  Methods defined here:
 |  
 |  __init__(self, name, color, weight, dev_lang)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  introduceSelf(self)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from Robot:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

None
  • isinstance(var, class): 可檢查 var 是否為 class 的 instance,可一併檢查是否為繼承的
print(isinstance(r1, MicroRobot))  >> True
print(isinstance(r1, Robot))       >> True
print(isinstance(r1, Person))      >> False

參考文獻

About the Author

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

You may also like these