Polymorphism in Python(with Examples) - Programiz

文章推薦指數: 80 %
投票人數:10人

Polymorphism is a very important concept in programming. It refers to the use of a single type entity (method, operator or object) to represent different types ... CourseIndex ExploreProgramiz Python JavaScript SQL C C++ Java Kotlin Swift C# DSA LearnPythonpractically andGetCertified. ENROLL PopularTutorials GettingStartedWithPython PythonifStatement whileLoopinPython PythonLists DictionariesinPython StartLearningPython PopularExamples Addtwonumbers Checkprimenumber Findthefactorialofanumber PrinttheFibonaccisequence Checkleapyear ExplorePythonExamples ReferenceMaterials Built-inFunctions ListMethods DictionaryMethods StringMethods Viewall LearningPaths Challenges LearnPythonInteractively TryforFree Courses BecomeaPythonMaster BecomeaCMaster BecomeaJavaMaster ViewallCourses Python JavaScript SQL C C++ Java Kotlin Swift C# DSA LearnPythonpractically andGetCertified. ENROLLFORFREE! PopularTutorials GettingStartedWithPython PythonifStatement whileLoopinPython PythonLists DictionariesinPython StartLearningPython AllPythonTutorials ReferenceMaterials Built-inFunctions ListMethods DictionaryMethods StringMethods Viewall Python JavaScript C C++ Java Kotlin LearnPythonpractically andGetCertified. ENROLLFORFREE! PopularExamples Addtwonumbers Checkprimenumber Findthefactorialofanumber PrinttheFibonaccisequence Checkleapyear AllPythonExamples LearnPythonInteractively PythonIntroduction GettingStarted KeywordsandIdentifier Statements&Comments PythonVariables PythonDataTypes PythonTypeConversion PythonI/OandImport PythonOperators PythonNamespace PythonFlowControl Pythonif...else PythonforLoop PythonwhileLoop Pythonbreakandcontinue PythonPass PythonFunctions PythonFunction FunctionArgument PythonRecursion AnonymousFunction Global,LocalandNonlocal PythonGlobalKeyword PythonModules PythonPackage PythonDatatypes PythonNumbers PythonList PythonTuple PythonString PythonSet PythonDictionary PythonFiles PythonFileOperation PythonDirectory PythonException ExceptionHandling User-definedException PythonObject&Class PythonOOP PythonClass PythonInheritance MultipleInheritance OperatorOverloading PythonAdvancedTopics PythonIterator PythonGenerator PythonClosure PythonDecorators PythonProperty PythonRegEx PythonExamples PythonDateandtime PythondatetimeModule Pythondatetime.strftime() Pythondatetime.strptime() Currentdate&time Getcurrenttime Timestamptodatetime PythontimeModule Pythontime.sleep() RelatedTopics PythonObjectOrientedProgramming Pythonsuper() PythonInheritance Pythonobject() PythonOperatorOverloading PythonObjectsandClasses PolymorphisminPython Inthistutorial,wewilllearnaboutpolymorphism,differenttypesofpolymorphism,andhowwecanimplementtheminPythonwiththehelpofexamples. WhatisPolymorphism? Theliteralmeaningofpolymorphismistheconditionofoccurrenceindifferentforms. Polymorphismisaveryimportantconceptinprogramming.Itreferstotheuseofasingletypeentity(method,operatororobject)torepresentdifferenttypesindifferentscenarios. Let'stakeanexample: Example1:Polymorphisminadditionoperator Weknowthatthe+operatorisusedextensivelyinPythonprograms.But,itdoesnothaveasingleusage. Forintegerdatatypes,+operatorisusedtoperformarithmeticadditionoperation. num1=1 num2=2 print(num1+num2) Hence,theaboveprogramoutputs3. Similarly,forstringdatatypes,+operatorisusedtoperformconcatenation. str1="Python" str2="Programming" print(str1+""+str2) Asaresult,theaboveprogramoutputsPythonProgramming. Here,wecanseethatasingleoperator+hasbeenusedtocarryoutdifferentoperationsfordistinctdatatypes.ThisisoneofthemostsimpleoccurrencesofpolymorphisminPython. FunctionPolymorphisminPython TherearesomefunctionsinPythonwhicharecompatibletorunwithmultipledatatypes. Onesuchfunctionisthelen()function.ItcanrunwithmanydatatypesinPython.Let'slookatsomeexampleusecasesofthefunction. Example2:Polymorphiclen()function print(len("Programiz")) print(len(["Python","Java","C"])) print(len({"Name":"John","Address":"Nepal"})) Output 9 3 2 Here,wecanseethatmanydatatypessuchasstring,list,tuple,set,anddictionarycanworkwiththelen()function.However,wecanseethatitreturnsspecificinformationaboutspecificdatatypes. Polymorphisminlen()functioninPythonClassPolymorphisminPython PolymorphismisaveryimportantconceptinObject-OrientedProgramming. TolearnmoreaboutOOPinPython,visit:PythonObject-OrientedProgramming WecanusetheconceptofpolymorphismwhilecreatingclassmethodsasPythonallowsdifferentclassestohavemethodswiththesamename. Wecanthenlatergeneralizecallingthesemethodsbydisregardingtheobjectweareworkingwith.Let'slookatanexample: Example3:PolymorphisminClassMethods classCat: def__init__(self,name,age): self.name=name self.age=age definfo(self): print(f"Iamacat.Mynameis{self.name}.Iam{self.age}yearsold.") defmake_sound(self): print("Meow") classDog: def__init__(self,name,age): self.name=name self.age=age definfo(self): print(f"Iamadog.Mynameis{self.name}.Iam{self.age}yearsold.") defmake_sound(self): print("Bark") cat1=Cat("Kitty",2.5) dog1=Dog("Fluffy",4) foranimalin(cat1,dog1): animal.make_sound() animal.info() animal.make_sound() Output Meow Iamacat.MynameisKitty.Iam2.5yearsold. Meow Bark Iamadog.MynameisFluffy.Iam4yearsold. Bark Here,wehavecreatedtwoclassesCatandDog.Theyshareasimilarstructureandhavethesamemethodnamesinfo()andmake_sound(). However,noticethatwehavenotcreatedacommonsuperclassorlinkedtheclassestogetherinanyway.Eventhen,wecanpackthesetwodifferentobjectsintoatupleanditeratethroughitusingacommonanimalvariable.Itispossibleduetopolymorphism. PolymorphismandInheritance Likeinotherprogramminglanguages,thechildclassesinPythonalsoinheritmethodsandattributesfromtheparentclass.Wecanredefinecertainmethodsandattributesspecificallytofitthechildclass,whichisknownasMethodOverriding. Polymorphismallowsustoaccesstheseoverriddenmethodsandattributesthathavethesamenameastheparentclass. Let'slookatanexample: Example4:MethodOverriding frommathimportpi classShape: def__init__(self,name): self.name=name defarea(self): pass deffact(self): return"Iamatwo-dimensionalshape." def__str__(self): returnself.name classSquare(Shape): def__init__(self,length): super().__init__("Square") self.length=length defarea(self): returnself.length**2 deffact(self): return"Squareshaveeachangleequalto90degrees." classCircle(Shape): def__init__(self,radius): super().__init__("Circle") self.radius=radius defarea(self): returnpi*self.radius**2 a=Square(4) b=Circle(7) print(b) print(b.fact()) print(a.fact()) print(b.area()) Output Circle Iamatwo-dimensionalshape. Squareshaveeachangleequalto90degrees. 153.93804002589985 Here,wecanseethatthemethodssuchas__str__(),whichhavenotbeenoverriddeninthechildclasses,areusedfromtheparentclass. Duetopolymorphism,thePythoninterpreterautomaticallyrecognizesthatthefact()methodforobjecta(Squareclass)isoverridden.So,itusestheonedefinedinthechildclass. Ontheotherhand,sincethefact()methodforobjectbisn'toverridden,itisusedfromtheParentShapeclass. PolymorphisminparentandchildclassesinPythonNote:MethodOverloading,awaytocreatemultiplemethodswiththesamenamebutdifferentarguments,isnotpossibleinPython. TableofContents WhatisPolymorphism? FunctionPolymorphisminPython ClassPolymorphisminPython PolymorphismandInheritance Shareon: Didyoufindthisarticlehelpful? Sorryaboutthat. Howcanweimproveit? Feedback* Leavethisfieldblank RelatedTutorialsPythonTutorialPythonObjectOrientedProgrammingPythonLibraryPythonsuper()PythonTutorialPythonInheritancePythonLibraryPythonobject() TryPROforFREE LearnPythonInteractively



請為這篇文章評分?