Polymorphism in Python - PYnative

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

Polymorphism in Python is the ability of an object to take many forms. In simple words, polymorphism allows us to perform the same action in ... Home»Python»PythonObject-OrientedProgramming(OOP)»PolymorphisminPython Object-OrientedProgramming(OOP)hasfouressentialcharacteristics:abstraction,encapsulation,inheritance,andpolymorphism. ThislessonwillcoverwhatpolymorphismisandhowtoimplementtheminPython.Also,you’lllearnhowtoimplementpolymorphismusingfunctionoverloading,methodoverriding,andoperatoroverloading. TableofcontentsWhatisPolymorphisminPython?PolymorphisminBuilt-infunctionlen()PolymorphismWithInheritanceExample:MethodOverridingOverrrideBuilt-inFunctionsPolymorphismInClassmethodsPolymorphismwithFunctionandObjectsPolymorphismInBuilt-inMethodsMethodOverloadingOperatorOverloadinginPythonOverloading+operatorforcustomobjectsOverloadingthe*OperatorMagicMethods WhatisPolymorphisminPython? PolymorphisminPythonistheabilityofanobjecttotakemanyforms.Insimplewords,polymorphismallowsustoperformthesameactioninmanydifferentways. Forexample,Jessaactsasanemployeewhensheisattheoffice.However,whensheisathome,sheactslikeawife.Also,sherepresentsherselfdifferentlyindifferentplaces.Therefore,thesamepersontakesdifferentformsasperthesituation. Apersontakesdifferentforms Inpolymorphism,amethodcanprocessobjectsdifferentlydependingontheclasstypeordatatype.Let’sseesimpleexamplestounderstanditbetter. PolymorphisminBuilt-infunctionlen() Thebuilt-infunctionlen()calculatesthelengthofanobjectdependinguponitstype.Ifanobjectisastring,itreturnsthecountofcharacters,andIfanobjectisalist,itreturnsthecountofitemsinalist. Thelen()methodtreatsanobjectasperitsclasstype. Example: students=['Emma','Jessa','Kelly'] school='ABCSchool' #calculatecount print(len(students)) print(len(school)) Output 3 10 Polymorphiclen()function PolymorphismWithInheritance Polymorphismismainlyusedwithinheritance.Ininheritance,childclassinheritstheattributesandmethodsofaparentclass.Theexistingclassiscalledabaseclassorparentclass,andthenewclassiscalledasubclassorchildclassorderivedclass. Usingmethodoverridingpolymorphismallowsustodefinesmethodsinthechildclassthathavethesamenameasthemethodsintheparentclass.Thisprocessofre-implementingtheinheritedmethodinthechildclassisknownasMethodOverriding. Advantageofmethodoverriding Itiseffectivewhenwewanttoextendthefunctionalitybyalteringtheinheritedmethod.Orthemethodinheritedfromtheparentclassdoesn’tfulfilltheneedofachildclass,soweneedtore-implementthesamemethodinthechildclassinadifferentway.Methodoverridingisusefulwhenaparentclasshasmultiplechildclasses,andoneofthatchildclasswantstoredefinethemethod.Theotherchildclassescanusetheparentclassmethod.Duetothis,wedon’tneedtomodificationtheparentclasscode Inpolymorphism,Pythonfirstcheckstheobject’sclasstypeandexecutestheappropriatemethodwhenwecallthemethod.Forexample,IfyoucreatetheCarobject,thenPythoncallsthespeed()methodfromaCarclass. Let’sseehowitworkswiththehelpofanexample. Example:MethodOverriding Inthisexample,wehaveavehicleclassasaparentanda‘Car’and‘Truck’asitssub-class.Buteachvehiclecanhaveadifferentseatingcapacity,speed,etc.,sowecanhavethesameinstancemethodnameineachclassbutwithadifferentimplementation.Usingthiscodecanbeextendedandeasilymaintainedovertime. PolymorphismwithInheritance classVehicle: def__init__(self,name,color,price): self.name=name self.color=color self.price=price defshow(self): print('Details:',self.name,self.color,self.price) defmax_speed(self): print('Vehiclemaxspeedis150') defchange_gear(self): print('Vehiclechange6gear') #inheritfromvehicleclass classCar(Vehicle): defmax_speed(self): print('Carmaxspeedis240') defchange_gear(self): print('Carchange7gear') #CarObject car=Car('Carx1','Red',20000) car.show() #callsmethodsfromCarclass car.max_speed() car.change_gear() #VehicleObject vehicle=Vehicle('Truckx1','white',75000) vehicle.show() #callsmethodfromaVehicleclass vehicle.max_speed() vehicle.change_gear() Output: Details:Carx1Red20000 Carmaxspeedis240 Carchange7gear Details:Truckx1white75000 Vehiclemaxspeedis150 Vehiclechange6gear Asyoucansee,duetopolymorphism,thePythoninterpreterrecognizesthatthemax_speed()andchange_gear()methodsareoverriddenforthecarobject.So,itusestheonedefinedinthechildclass(Car) Ontheotherhand,theshow()methodisn’toverriddenintheCarclass,soitisusedfromtheVehicleclass. OverrrideBuilt-inFunctions InPython,wecanchangethedefaultbehaviorofthebuilt-infunctions.Forexample,wecanchangeorextendthebuilt-infunctionssuchaslen(),abs(),ordivmod()byredefiningtheminourclass.Let’sseetheexample. Example Inthisexample,wewillredefinethefunctionlen() classShopping: def__init__(self,basket,buyer): self.basket=list(basket) self.buyer=buyer def__len__(self): print('Redefinelength') count=len(self.basket) #counttotalitemsinadifferentway #pairofshoesandshir+pant returncount*2 shopping=Shopping(['Shoes','dress'],'Jessa') print(len(shopping)) Output Redefinelength 4 PolymorphismInClassmethods Polymorphismwithclassmethodsisusefulwhenwegroupdifferentobjectshavingthesamemethod.wecanaddthemtoalistoratuple,andwedon’tneedtochecktheobjecttypebeforecallingtheirmethods.Instead,Pythonwillcheckobjecttypeatruntimeandcallthecorrectmethod.Thus,wecancallthemethodswithoutbeingconcernedaboutwhichclasstypeeachobjectis.Weassumethatthesemethodsexistineachclass. Pythonallowsdifferentclassestohavemethodswiththesamename. Let’sdesignadifferentclassinthesamewaybyaddingthesamemethodsintwoormoreclasses.Next,createanobjectofeachclassNext,addallobjectsinatuple.Intheend,iteratethetupleusingaforloopandcallmethodsofaobjectwithoutcheckingitsclass. Example Inthebelowexample,fuel_type()andmax_speed()aretheinstancemethodscreatedinbothclasses. classFerrari: deffuel_type(self): print("Petrol") defmax_speed(self): print("Maxspeed350") classBMW: deffuel_type(self): print("Diesel") defmax_speed(self): print("Maxspeedis240") ferrari=Ferrari() bmw=BMW() #iterateobjectsofsametype forcarin(ferrari,bmw): #callmethodswithoutcheckingclassofobject car.fuel_type() car.max_speed() Output Petrol Maxspeed350 Diesel Maxspeedis240 Asyoucansee,wehavecreatedtwoclassesFerrariandBMW.Theyhavethesameinstancemethodnamesfuel_type()andmax_speed().However,wehavenotlinkedboththeclassesnorhaveweusedinheritance. Wepackedtwodifferentobjectsintoatupleanditeratethroughitusingacarvariable.ItispossibleduetopolymorphismbecausewehaveaddedthesamemethodinbothclassesPythonfirstcheckstheobject’sclasstypeandexecutesthemethodpresentinitsclass. PolymorphismwithFunctionandObjects Wecancreatepolymorphismwithafunctionthatcantakeanyobjectasaparameterandexecuteitsmethodwithoutcheckingitsclasstype.Usingthis,wecancallobjectactionsusingthesamefunctioninsteadofrepeatingmethodcalls. Example classFerrari: deffuel_type(self): print("Petrol") defmax_speed(self): print("Maxspeed350") classBMW: deffuel_type(self): print("Diesel") defmax_speed(self): print("Maxspeedis240") #normalfunction defcar_details(obj): obj.fuel_type() obj.max_speed() ferrari=Ferrari() bmw=BMW() car_details(ferrari) car_details(bmw) Output Petrol Maxspeed350 Diesel Maxspeedis240 PolymorphismInBuilt-inMethods ThewordpolymorphismistakenfromtheGreekwordspoly(many)andmorphism(forms).Itmeansamethodcanprocessobjectsdifferentlydependingontheclasstypeordatatype. Thebuilt-infunctionreversed(obj)returnstheiterablebyreversingthegivenobject.Forexample,ifyoupassastringtoit,itwillreverseit.Butifyoupassalistofstringstoit,itwillreturntheiterablebyreversingtheorderofelements(itwillnotreversetheindividualstring). Letusseehowabuilt-inmethodprocessobjectshavingdifferentdatatypes. Example: students=['Emma','Jessa','Kelly'] school='ABCSchool' print('Reversestring') foriinreversed('PYnative'): print(i,end='') print('\nReverselist') foriinreversed(['Emma','Jessa','Kelly']): print(i,end='') Output: Reversestring evitanYP Reverselist KellyJessaEmma MethodOverloading Theprocessofcallingthesamemethodwithdifferentparametersisknownasmethodoverloading.Pythondoesnotsupportmethodoverloading.Pythonconsidersonlythelatestdefinedmethodevenifyouoverloadthemethod.PythonwillraiseaTypeErrorifyouoverloadthemethod. Example defaddition(a,b): c=a+b print(c) defaddition(a,b,c): d=a+b+c print(d) #thebelowlineshowsanerror #addition(4,5) #Thislinewillcallthesecondproductmethod addition(3,7,5) Toovercometheaboveproblem,wecanusedifferentwaystoachievethemethodoverloading.InPython,tooverloadtheclassmethod,weneedtowritethemethod’slogicsothatdifferentcodeexecutesinsidethefunctiondependingontheparameterpasses. Forexample,thebuilt-infunctionrange()takesthreeparametersandproducedifferentresultdependinguponthenumberofparameterspassedtoit. Example: foriinrange(5):print(i,end=',') print() foriinrange(5,10):print(i,end=',') print() foriinrange(2,12,2):print(i,end=',') Output: 0,1,2,3,4, 5,6,7,8,9, 2,4,6,8,10, Let’sassumewehaveanarea()methodtocalculatetheareaofasquareandrectangle.Themethodwillcalculatetheareadependinguponthenumberofparameterspassedtoit. Ifoneparameterispassed,thentheareaofasquareiscalculatedIftwoparametersarepassed,thentheareaofarectangleiscalculated. Example:User-definedpolymorphicmethod classShape: #functionwithtwodefaultparameters defarea(self,a,b=0): ifb>0: print('AreaofRectangleis:',a*b) else: print('AreaofSquareis:',a**2) square=Shape() square.area(5) rectangle=Shape() rectangle.area(5,3) Output: AreaofSquareis:25 AreaofRectangleis:15 OperatorOverloadinginPython Operatoroverloadingmeanschangingthedefaultbehaviorofanoperatordependingontheoperands(values)thatweuse.Inotherwords,wecanusethesameoperatorformultiplepurposes. Forexample,the+operatorwillperformanarithmeticadditionoperationwhenusedwithnumbers.Likewise,itwillperformconcatenationwhenusedwithstrings. Theoperator + isusedtocarryoutdifferentoperationsfordistinctdatatypes.ThisisoneofthemostsimpleoccurrencesofpolymorphisminPython. Example: #add2numbers print(100+200) #concatenatetwostrings print('Jess'+'Roy') #mergertwolist print([10,20,30]+['jessa','emma','kelly']) Output: 300 JessRoy [10,20,30,'jessa','emma','kelly'] Overloading+operatorforcustomobjects Supposewehavetwoobjects,andwewanttoaddthesetwoobjectswithabinary+operator.However,itwillthrowanerrorifweperformadditionbecausethecompilerdoesn’taddtwoobjects.Seethefollowingexampleformoredetails. Example: classBook: def__init__(self,pages): self.pages=pages #creatingtwoobjects b1=Book(400) b2=Book(300) #addtwoobjects print(b1+b2) Output TypeError:unsupportedoperandtype(s)for+:'Book'and'Book' Wecanoverload+operatortoworkwithcustomobjectsalso.Pythonprovidessomespecialormagicfunctionthatisautomaticallyinvokedwhenassociatedwiththatparticularoperator. Forexample,whenweusethe+operator,themagicmethod__add__()isautomaticallyinvoked.Internally+operatorisimplementedbyusing__add__()method.Wehavetooverridethismethodinourclassifyouwanttoaddtwocustomobjects. Example: classBook: def__init__(self,pages): self.pages=pages #Overloading+operatorwithmagicmethod def__add__(self,other): returnself.pages+other.pages b1=Book(400) b2=Book(300) print("Totalnumberofpages:",b1+b2) Output Totalnumberofpages:700 Overloadingthe*Operator The*operatorisusedtoperformthemultiplication.Let’sseehowtooverloadittocalculatethesalaryofanemployeeforaspecificperiod.Internally*operatorisimplementedbyusingthe__mul__()method. Example: classEmployee: def__init__(self,name,salary): self.name=name self.salary=salary def__mul__(self,timesheet): print('Workedfor',timesheet.days,'days') #calculatesalary returnself.salary*timesheet.days classTimeSheet: def__init__(self,name,days): self.name=name self.days=days emp=Employee("Jessa",800) timesheet=TimeSheet("Jessa",50) print("salaryis:",emp*timesheet) Output Wrokedfor50days salaryis:40000 MagicMethods InPython,therearedifferentmagicmethodsavailabletoperformoverloadingoperations.Thebelowtableshowsthemagicmethodsnamestooverloadthemathematicaloperator,assignmentoperator,andrelationaloperatorsinPython. OperatorNameSymbolMagicmethodAddition+__add__(self,other)Subtraction-__sub__(self,other)Multiplication*__mul__(self,other)Division/__div__(self,other)FloorDivision//__floordiv__(self,other)Modulus%__mod__(self,other)Power**__pow__(self,other)Increment+=__iadd__(self,other)Decrement-=__isub__(self,other)Product*=__imul__(self,other)Division/+__idiv__(self,other)Modulus%=__imod__(self,other)Power**=__ipow__(self,other)Lessthan<__lt__>__gt__(self,other)Lessthanorequalto<=__le__(self,other)Greaterthanorequalto>=__ge__(self,other)Equalto==__eq__(self,other)Notequal!=__ne__(self,other)magicmethods Didyoufindthispagehelpful?Letothersknowaboutit.SharinghelpsmecontinuetocreatefreePythonresources. TweetF sharein shareP Pin AboutVishal FounderofPYnative.comIamaPythondeveloperandIlovetowritearticlestohelpdevelopers.FollowmeonTwitter.AllthebestforyourfuturePythonendeavors! RelatedTutorialTopics: PythonPythonObject-OrientedProgramming(OOP) PythonExercisesandQuizzes FreecodingexercisesandquizzescoverPythonbasics,datastructure,dataanalytics,andmore. 15+Topic-specificExercisesandQuizzesEachExercisecontains10questionsEachQuizcontains12-15MCQ Exercises Quizzes PostedIn PythonPythonObject-OrientedProgramming(OOP) TweetF sharein shareP Pin PythonOOP PythonOOP ClassesandObjectsinPython ConstructorsinPython PythonDestructors EncapsulationinPython PolymorphisminPython InheritanceinPython PythonInstanceVariables PythonInstanceMethods PythonClassVariables PythonClassMethod PythonStaticMethod PythonClassMethodvs.StaticMethodvs.InstanceMethod PythonOOPexercise AllPythonTopics PythonBasics PythonExercises PythonQuizzes PythonFileHandling PythonOOP PythonDateandTime PythonRandom PythonRegex PythonPandas PythonDatabases PythonMySQL PythonPostgreSQL PythonSQLite PythonJSON AboutPYnative PYnative.comisforPythonlovers.Here,YoucangetTutorials,Exercises,andQuizzestopracticeandimproveyourPythonskills. ExplorePython LearnPython PythonBasics PythonDatabases PythonExercises PythonQuizzes OnlinePythonCodeEditor PythonTricks FollowUs TogetNewPythonTutorials,Exercises,andQuizzes Twitter Facebook Sitemap LegalStuff AboutUs ContactUs Weusecookiestoimproveyourexperience.WhileusingPYnative,youagreetohavereadandacceptedourTermsOfUse,CookiePolicy,andPrivacyPolicy. Copyright© 2018–2022pynative.com Searchfor:SearchButton



請為這篇文章評分?