您用方法(或方法)定義了基類。 然後,您創建從基類繼承的派生類,並覆蓋方法以提供特定的實現。 當您在對像上調用該方法時,Python將使用對像類中定義的實現。這被稱為運行時多態性,因為使用鴨子鍵入:
<code class="python">class Animal: def speak(self): raise NotImplementedError("Subclasses must implement this method") class Dog(Animal): def speak(self): return "Woof!" class Cat(Animal): def speak(self): return "Meow!" animals = [Dog(), Cat()] for animal in animals: print(animal.speak()) # Output: Woof! Meow!</code>
鴨>鴨子鍵入是一種更靈活的方法。 它依賴於這樣的原則:“如果它像鴨子一樣行走,像鴨子一樣,那一定是鴨子。” 您不需要明確的繼承;如果對象具有必要的方法,則可以通過多態使用。 這通常與界面或抽象基類(ABC)結合使用以獲得更好的結構,但並不是嚴格要求的。
<code class="python">class Bird: def fly(self): print("I'm flying!") class Airplane: def fly(self): print("I'm an airplane flying!") things_that_fly = [Bird(), Airplane()] for thing in things_that_fly: thing.fly() # Output: I'm flying! I'm an airplane flying!</code>
speak
fly
在這兩個示例中,
>
><code class="python">class Animal: def speak(self): raise NotImplementedError("Subclasses must implement this method") class Dog(Animal): def speak(self): return "Woof!" class Cat(Animal): def speak(self): return "Meow!" animals = [Dog(), Cat()] for animal in animals: print(animal.speak()) # Output: Woof! Meow!</code>>您能否提供一個實用的示例,可以在Python Project中展示多態性的python Project?我們可以使用多態性來處理不同的形狀,而無需為每個形狀提供單獨的繪圖功能:
area
perimeter
>本示例通過繼承來展示多態性。 Shape
和
以上是如何在Python中使用多態性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!