What is Polymorphism in Python? - Educative.io

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

Like other languages that accommodate object-oriented programming (OOP), Python is polymorphic. This means that a single operator, function, ... BlogHomeSolutionsEducativeEnterpriseEnablementplatformDevelopersLearnnewtechnologiesProductsCoursesforEnterpriseSuperchargeyourengineeringteamCoursesforIndividualsWorldclasscoursesOnboardingOnboardnewhiresfasterAssessmentsMeasureyourSkillScorePersonalizedLearningPlansPersonalizedPlansforyourgoalsProjectsBuildrealworldapplicationsAnswersTrustedAnswerstoDeveloperQuestionsPricingForEnterpriseTailoredforyourteamForIndividualsStayaheadofthecurveLogInJoin forfreeWhatisPolymorphisminPython?May31,2022-6minreadCaseyJergensonPythonisoneofthemostpopularprogramminglanguagesduetoitsversatilityanditsuser-friendlysyntax.Likeotherlanguagesthataccommodateobject-orientedprogramming(OOP),Pythonispolymorphic.Thismeansthatasingleoperator,function,orclassmethodinPythoncanhavemultipleuses.Thesevarioususesmightbechallengingtolearn,buttheyultimatelymakePythonamoreefficientlanguage. Today,we’lldiscusspolymorphismandhowitworksinPython. We’llcoverthefollowingtopics: Whatispolymorphism? ExamplesofpolymorphisminPython Pythonpolymorphismtutorial Wrappingupandnextsteps Whatispolymorphism? Polymorphismistheprinciplethatonekindofthingcantakeavarietyofforms.Inthecontextofprogramming,thismeansthatasingleentityinaprogramminglanguagecanbehaveinmultiplewaysdependingonthecontext.It’ssimilartohowawordlike“express”canactasaverbinonesentence,anouninanothersentence,andanadjectiveinathirdsentence.Thesequenceoflettersonthepagedoesn’tchange,butthemeaningtheyaddtothesentenceisfundamentallydifferentineachcase.Likewise,inpolymorphicprogramminglanguages,asingleentitycanactdifferentlyindifferentcontexts. ExamplesofpolymorphisminPython PolymorphismisabasicconditionofPython,anditaffectshowthelanguageworksatmultiplelevels.Today,we’llfocusonthepolymorphismofoperators,functions,andclassmethodsinPython. OperatorPolymorphism Operatorpolymorphism,oroperatoroverloading,meansthatonesymbolcanbeusedtoperformmultipleoperations.Oneofthesimplestexamplesofthisistheadditionoperator+.Python’sadditionoperatorworksdifferentlyinrelationtodifferentdatatypes. Forexample,ifthe+operatesontwointegers,theresultisadditive,returningthesumofthetwointegers. int1=10 int2=15 print(int1+int2) #returns25Intheexampleabove,the+operatoradds10and15,suchthattheoutputis25. However,iftheadditionoperatorisusedontwostrings,itconcatenatesthestrings.Here’sanexampleofhowthe+operatoractsonstringdatatypes. str1="10" str2="15" print(str1+str2) #returns1015Inthiscase,theoutputis1015becausethe+operatorconcatenatesthestrings“10”and“15”.Thisisoneexampleofhowasingleoperatorcanperformdistinctoperationsindifferentcontexts. FunctionPolymorphism CertainfunctionsinPythonarepolymorphicaswell,meaningthattheycanactonmultipledatatypesandstructurestoyielddifferentkindsofinformation. Python’sbuilt-inlen()function,forinstance,canbeusedtoreturnthelengthofanobject.However,itwillmeasurethelengthoftheobjectdifferentlydependingontheobject’sdatatypeandstructure.Forinstance,iftheobjectisastring,thelen()functionwillreturnthenumberofcharactersinthestring.Iftheobjectisalist,itwillreturnthenumberofentriesinthelist. Here’sanexampleofhowthelen()functionactsonstringsandlists: str1="animal" print(len(str1)) #returns6 list1=["giraffe","lion","bear","dog"] print(len(list1)) #returns4Theoutputsare6and4,respectively,becausethelen()functioncountsthenumberofcharactersinastringandthenumberofentriesinalist.Thefunctionoperatesdifferentlydependingonthenatureofthedatait’sactingon. ClassandMethodPolymorphism Python’spolymorphicnaturemakesiteasiertorepurposeclassesandmethods.Rememberthataclassislikeablueprint,andanobjectisaconcreteinstantiationofthatblueprint.So,amethodthatispartofaclasswillreoccurintheobjectsthatinstantiatethatclass.Likewise,ifyougenerateanewclassfromapreexistingclass,thenewclasswillinheritthemethodsofthepreexistingclass.Thenewclassinthisscenarioiscalleda“childclass,”whilethepreexistingclassiscalledthe“parentclass.” Here’sanexampleofaparentclassandachildclassthat’sderivedfromit.Notethattheparentclassestablishesthemethodtype,sothechildclassinheritsthatmethod.Themethodisredefinedinthechildclass,however,suchthatobjectsinstantiatedfromthechildclassusetheredefinedmethod.Thisiscalled“methodoverriding.” #DefineparentclassAnimal classAnimal: #Definemethod deftype(self): print("animal") #DefinechildclassDog classDog(Animal): deftype(self): print("dog") #Initializeobjects obj_bear=Animal() obj_terrier=Dog() obj_bear.type() #returnsanimal obj_terrier.type() #returnsdogThemethodnametyperemainsthesameinthechildclass,butithasbeenoverridden.Anobjectinstantiatedfromtheparentclasswillusetheoriginalmethodasitisdefinedintheparentclass,whileamethodinstantiatedfromthechildclasswillusetheoverriddenmethod.Therefore,theoutputsfromtheprogramaboveareanimalanddog,respectively. Asimilarprincipleappliestoclassesthatareindependentofeachother.Forinstance,imaginethatyou’recreatingtwonewclasses:LionandGiraffe. classLion: defdiet(self): print(“carnivore”) classGiraffe: defdiet(self): print(“herbivore”) obj_lion=Lion() obj_giraffe=Giraffe() obj_lion.diet() #returnscarnivore obj_giraffe.diet() #returnsherbivoreTheoutputsfromthisprogramarecarnivoreandherbivore,respectively.Thetwoclassesbothusethemethodnamediet,buttheydefinethosemethodsdifferently.AnobjectinstantiatedfromtheLionclasswillusethemethodasitisdefinedinthatclass.TheGiraffeclassmayhaveamethodwiththesamename,butobjectsinstantiatedfromtheLionclasswon’tinteractwithit. Gethands-onwithPythontoday. Tryoneofour300+coursesandlearningpaths:PythonforProgrammers. Startlearning Pythonpolymorphismtutorial Thebestwaytolearnanewcodingskillisbyactuallypracticingit.Tryrunningthecodeintheexamplesbelowtoseepolymorphisminaction! First,let’spracticeoperatorpolymorphism.We’llusethe+operatortoaddtheintegers2and3whileconcatenatingthestrings“2”and“3”. int1=2 int2=3 print(int1+int2) str1="2" str2="3" print(str1+str2)RunNext,tryusingthelen()functiontomeasurethelengthofthestring“numbers”andthelist[“1”,“2”,“3”,“4”]. str1="numbers" print(len(str1)) list1=["1","2","3","4"] print(len(list1))RunClassmethodpolymorphismisalittlemorecomplicated.Inthecodeblockbelow,we’vecreatedaparentclassFishanddefinedaclassmethodtype.We’vethencreatedachildclasscalledSharkwhileoverridingthetypemethodsothatobjectsinstantiatedfromtheSharkclassusetheoverriddenmethod. classFish: deftype(self): print("fish") classShark(Fish): deftype(self): print("shark") obj_goldfish=Fish() obj_hammerhead=Shark() obj_goldfish.type() obj_hammerhead.type()RunFinally,below,we’vecreatedtwonew,independentclasses:TurtleandFrog.WhenyouinstantiateanobjectfromtheTurtleclass,theobjectwillusethetypemethodasitisdefinedinthatclass.ThesamewillbetrueofobjectsinstantiatedfromtheFrogclass,despitethefactthatthemethodshavethesamename. classTurtle: deftype(self): print("turtle") classFrog: deftype(self): print("frog") obj_sea_turtle=Turtle() obj_treefrog=Frog() obj_sea_turtle.type() obj_treefrog.type()Run Wrappingupandnextsteps Polymorphismisanimportantelementofobject-orientedprogramminginPython.PolymorphismmakesPythonamoreversatileandefficientlanguage.Itallowsyoutouseasingleoperatororfunctiontoperformmultipletasks.Italsoallowsyoutoreusemethodnameswhileredefiningthemfortheuniquepurposesofdifferentclasses. Learninghowtomakeuseofthepolymorphismofoperators,functions,andclassmethodsmightbechallenging,butonceyou’vedoneso,you’llbeamoreadeptprogrammer. TolearnmoreaboutusingPython,considerexploringEducative’sPythonforProgrammerslearningpath.Overthecourseoffourmodules,you’lllearnthefundamentalsofPythonandthengraduallyprogresstomoreadvancedskills.Ifyou’realreadyfamiliarwithPythonandarepreparingforaninterview,considertheAcethePythonCodingInterviewlearningpath.ItwillhelpyoubrushuponyourPythonskillswhilealsogivingyouopportunitiestopracticerealinterviewquestions. Happylearning! ContinueLearningAboutPython WrappingyourheadaroundneuralnetworksinPython 7topPythonlibrariesfordatascienceandmachinelearning WhatcanyoudowithPython?5real-worldapplications WRITTENBYCaseyJergensonJoinacommunityofmorethan1.4millionreaders.Afree,bi-monthlyemailwitharoundupofEducative'stoparticlesandcodingtips.SubscribeLearnin-demandtechskillsinhalfthetimeSOLUTIONSForEnterpriseForIndividualsForHR&RecruitingForBootcampsPRODUCTSEducativeLearningEducativeOnboardingEducativeSkillAssessmentsEducativeProjectsPricingForEnterpriseForIndividualsFreeTrialLEGALPrivacyPolicyCookieSettingsTermsofServiceBusinessTermsofServiceCONTRIBUTEBecomeanAuthorBecomeanAffiliateBecomeaContributorRESOURCESEducativeBlogEMHubEducativeSessionsEducativeAnswersABOUTUSOurTeamCareersHiringFrequentlyAskedQuestionsContactUsPressMOREGitHubStudentsScholarshipCourseCatalogEarlyAccessCoursesEarnReferralCreditsCodingInterview.comCopyright©2022Educative,Inc.Allrightsreserved.



請為這篇文章評分?