Python 是否支援多型性


是的,Python 支援多型性。多型性一詞意味著具有多種形式。多型性是 Python 中類定義的一個重要特性,在跨類或子類使用同名方法時使用。

多型性可以透過繼承來實現,其中子類利用基類方法或覆蓋它們。

多型性有兩種型別

  • 函式過載
  • 方法重寫

函式過載

當一個類中的兩個或更多個方法具有相同的方法名但不同的引數時,就會發生過載。

方法重寫

方法重寫是指同時具有相同的方法名和引數的方法(即方法簽名)。其中一個方法在父類中,另一個方法在子類中。

示例

class Fish(): def swim(self): print("The Fish is swimming.") def swim_backwards(self): print("The Fish can swim backwards, but can sink backwards.") def skeleton(self): print("The fish's skeleton is made of cartilage.") class Clownfish(): def swim(self): print("The clownfish is swimming.") def swim_backwards(self): print("The clownfish can swim backwards.") def skeleton(self): print("The clownfish's skeleton is made of bone.") a = Fish() a.skeleton() b = Clownfish() b.skeleton()

輸出

The fish's skeleton is made of cartilage.
The clownfish's skeleton is made of bone.

更新時間:2022 年 8 月 12 日

988 人瀏覽

開啟你的事業

完成課程並獲得認證

開始
廣告
© . All rights reserved.