搜尋
首頁後端開發Python教學理解 Python 中的多態性

Understanding Polymorphism in Python

本文深入解釋了 Python 中的多態性,強調了它在物件導向程式設計中的作用。


多態性是一個希臘詞,意思是多種形狀或多種形式。多態性是物件導向程式設計(OOP)中的一個基本概念。 Python 是多態的,這意味著 Python 中的物件能夠採取多種形式。簡而言之,多態性允許我們以多種不同的方式執行相同的操作。 (Vishal,2021)此外,在 Python 中,一切都是物件/類別。 「Guido van Rossum 根據『一切都是一流』的原則設計了這個語言。他寫道:「我對 Python 的目標之一是讓所有物件都是『一流的』。我的意思是,我希望所有可以用該語言命名的物件(例如整數、字串、函數、類別、模組、方法等)都具有平等的地位。 」 (Klein,2022,1.物件導向程式設計)

要理解多態性,了解「鴨子類型」概念很重要。 「如果它看起來像鴨子並且嘎嘎叫起來像鴨子,那麼它可能是鴨子。」在程式設計中,這意味著物件的適用性是由某些方法和屬性的存在決定的,而不是物件的實際類型。在Python中,鴨子類型是一個概念,其中物件的「適用性」由以下因素決定:某些方法或屬性的存在,而不是物件的實際類型。換句話說,Python 中的多態性意味著單一運算子、函數或類別方法可以根據上下文具有多種形式/行為。

1。運算子多型
或者運算子重載允許運算子根據操作數類型執行不同的操作。 (傑根森,2022)

例如:
兩個整數

int_1 = 10
int_2 = 45
print(str(int_1 + int_2))
>>>
55

兩根弦

str_1 = “10”
str_2 = “45”
print(str_1 + str_2)
>>>
1045

2。函數多態性
像 len() 這樣的內建函數可以作用於多種資料類型(例如字串、列表),並為每種類型提供適當的測量長度。

例如:

str_1 = "polymorphic"
print(str(len(str_1)))
>>>
11

my_lst = [1, 2, 3, 4, 5]
print(str(len(my_lst))
>>>
5

3。類別方法多型
允許子類別覆寫從父類別繼承的方法。

例如:

#  Parent class
class Animal:
    def make_sound(self):
        pass

# Child Class
class Dog(Animal):
    def make_sound(self):
        return "Woof!"

# Child Class
class Cat(Animal):
    def make_sound(self):
        return "Meow!"
    def animal_sound(animal):
        print(animal.make_sound())
dog = Dog()
cat = Cat()
animal_sound(dog)  # Output: Woof!
animal_sound(cat)  # Output: Meow!

4。獨立的類別也可以定義具有相同名稱但行為不同的方法。

例如:

def enter_obj(obj):
    return obj.action() # Independent class
class Animal:
    def __init__(self, food):
        self.food = food
    # same name as the Circle method different functionality
    def action(self):
        print(f"eats {self.food}")# Independent class
class Circle:
        def __init__(self, radius):
            self.radius = radius
        # same name as the Animal method different functionality
        def action(self):
            return 3.14 * (self.radius ** 2)
cow = Animal("grass")
circ = Circle(7)
enter_obj(cow)print(str(enter_obj(circ))) 
>>> 
eats grass 
153.86

總之,多態性是Python的一個強大特性。它允許物件呈現多種形式並根據上下文表現出不同的行為。 Python 的鴨子類型透過專注於某些方法或屬性的存在而不是物件的實際類型來實現多態性。


參考文獻:

Jergenson, C.(2022 年,5 月 31 日)._ 什麼是 Python 中的多態性? _。有教育意義。 https://www.eduative.io/blog/what-is-polymorphism-python

Klein, B.(2022 年,2 月 1 日)。 物件導向程式設計/OPP。 python 課程。 https://python-course.eu/oop/object-oriented-programming.php

維沙爾。 (2021 年,10 月 21 日)。 Python 中的多態性。 PYnative。 https://pynative.com/python-polymorphism/


原於 2024 年 8 月 19 日發表於 Understanding Polymorphism in Python - Medium。

以上是理解 Python 中的多態性的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:編譯器還是解釋器?Python:編譯器還是解釋器?May 13, 2025 am 12:10 AM

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

python用於循環與循環時:何時使用哪個?python用於循環與循環時:何時使用哪個?May 13, 2025 am 12:07 AM

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

Python循環:最常見的錯誤Python循環:最常見的錯誤May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

對於循環和python中的循環時:每個循環的優點是什麼?對於循環和python中的循環時:每個循環的優點是什麼?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供應模擬性和可讀性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用