Ways to Achieve Multiple Constructors in Python
文章推薦指數: 80 %
Python Methods calling from __init__ as Multiple Constructors Skiptocontent Menu Menu HelloProgrammers,today’sarticleisaboutmultipleconstructorsinPython.Switchingtopythonfromanyotherprogramminglanguagehasalladvantagesexceptwhenitcomestomultipleconstructors.Pythondoesnotsupportmultipleconstructors.However,pythonofferssomeofthealternativewaystosupportmultipleconstructors.Wewilldiscusssomeofthosewayshere.Butbeforethatletmebriefyouaboutwhatistheneedformultipleconstructorsinaprogram. Multipleconstructionshelpyoutocustomizeyourclassaccordingtoitsparameters.Uponusingadifferentnumberofparameters,differentconstructionscanbetriggered.Unlikeotherprogramminglanguages,Pythonhasadifferentwayofhandlingmultipleparameters.We’llhavealookateachofthemindetail. Contents PythonMultipleConstructorsAndItsNeed:DifferentwaystogetMultipleConstructorsinPythonare:PythonConstructoroverloadingbasedonargumentsasMultipleConstructors:PythonMethodscallingfrom__init__asMultipleConstructors:@classmethoddecoratorasMultipleConstructors:MustReadConclusion: PythonMultipleConstructorsAndItsNeed: Multipleconstructorscometousewhenadefinedclasshastoperformdifferentfunctions.Andondifferentparametersorinstancesofaclass. Onwritingthesamemethodmultipletimesforaclass,thelastoneoverwritesallthepreviousconstructors.Sincemultipleconstructorsdonotworkwellwithpython,theclassconstructorsexhibitpolymorphism.Thismethodhelpstoreplicatethemultipleconstructorfeatureinpython. DifferentwaystogetMultipleConstructorsinPythonare: ConstructoroverloadingbasedonargumentsMethodscallingfrom__init__@classmethoddecorator PythonConstructoroverloadingbasedonargumentsasMultipleConstructors: EXAMPLE: classeaxmple: #constructoroverloading #basedonargs def__init__(self,*args): #ifargsaremorethan1 #sumofargs iflen(args)>1: self.answer=0 foriinargs: self.answer+=i #ifargisaninteger #squarethearg elifisinstance(args[0],integer): self.answer=args[0]*args[0] #ifargisstring #Printwithhello elifisinstance(args[0],str): self.answer="Hello!"+args[0]+"." e1=example(1,2,3,6,8) print("Sumoflist:",e1.answer) e2=example(6) print("Squareofinteger:",e2.answer) e3=example("Programmers") print("String:",e3.answer) OUTPUT: Sumoflist:20 Squareofinteger:36 String:Hello!Programmers EXPLANATION: Intheaboveexample,theansweristheinstancevariableoftheclassexample.Itsvaluedifferedindifferentinstancesinsidetheclassbasedonarguments.Aclasscanhavemultiplearguments.Therefore*argsisdefinedasatuplethatholdsdifferentargumentspassedtoit.Theargumentsareaccessibleusinganindex.Forinstance,asintheintegerandstringcase,sinceonlyoneargumentispassed,itisthusaccessedasargs[0].Whileforthesum,morethanoneargumentpassedtoitisaccessedbyusingaloop. PythonMethodscallingfrom__init__asMultipleConstructors: EXAMPLE: classequations: #singleconstructortocallothermethods def__init__(self,*abc): #when2argumentsarepassed iflen(abc)==2: self.ans=self.eq1(abc) #when3argumentsarepassed eliflen(abc)==3: self.ans=self.eq2(abc) #whenmorethan3argumentsarepassed else: self.ans=self.eq3(abc) defeq1(self,args): x=(args[0]*args[0])+(args[1]*args[1]) returny defeq2(self,args): y=args[0]+args[1]-args[2] returnx defeq3(self,args): temp=0 foriinrange(0,len(args)): temp+=args[i]*args[i] temp=temp/5.0 z=temp returnz abc1=equations(4,2) abc2=equations(4,2,3) abc3=equations(1,2,3,4,5) print("equation1:",abc1.ans) print("equation2:",abc2.ans) print("equation3:",abc3.ans) OUTPUT: equation1:12 equation2:17 equation3:11.0 EXPLANATION: Inthisexample,threeequationsperformedintheinstancesoftheclassare:equaton1–x=a2+b2equation2–y=a+b –c.Equation3–z=sumofthesquareofargumentspassed/5.0. equation1isfortwoarguments.equation2isforthreeandequation3formorethanthree. Usingamulticonstructorinpython,aclasshavingoneconstructor__init__isdefined.Itcanperformanyactiononthecreationofdifferentclassinstances.Aboveall,intheabovecode,equationstobeevaluatedarewrittenindifferentinstancesoftheclass.Aboveallthe__init__constructorcallsdifferentmethodstoreturntheanswerbasedonthenumberofargumentspassed. @classmethoddecoratorasMultipleConstructors: EXAMPLE: classequations: #basicconstructor def__init__(self,x): self.ans=x @classmethod defeq1(obj,args): #createanobjectfortheclasstoreturn a=obj((args[0]*args[0])+(args[1]*args[1]) returna @classmethod defeq2(obj,args): b=obj(args[0]+args[1]-args[2]) returnb @classmethod defeq3(obj,args): temp=0 #squareofeachelement foriinrange(0,len(args)): temp+=args[i]*args[i] temp=temp/5.0 z=obj(temp) returnz li=[[4,2],[4,2,3],[1,2,3,4,5]] i=0 #looptogetinputthreetimes whilei<3: input=li[i] #no.of.arguments=2 iflen(input)==2: p=equations.eq1(input) print("equation1:",p.ans) #no.of.arguments=3 eliflen(input)==3: p=equations.eq1(input) print("equation2:",p.ans) #Morethanthreearguments else: p=equations.eq3(input) print("equation3:",p.ans) #incrementloop i+=1 OUTPUT: equation1:12 equation2:17 equation3:11.0 EXPLANATION: Equationsperformedintheaboveexampleare:equaton1–x=a2+b2.Equation2–y=a+b –c.SimilarlyEquation3–z=sumofthesquareofargumentspassed/5.0. Whentwoargumentsarepassed,equation1isevaluated.Forthreearguments,equation2isperformed.Andformorethanthreearguments,equation3isevaluated. Instancesarenotcreatedfortheaboveclassinitially.Similarly,classmethodsaredefinedtoevaluatethevariousequationsusingthe@classmethoddecorator.Thereforetheyarenowcalledusingclassnames.Inaddition,wecreateobjectsinsidetheclassmethodsitselfaftertheevaluationoftheequations.Thereforetheinstancevariablereturnstheanswer. MustRead IntroductiontoPythonSuperWithExamplesPythonHelpFunctionWhyisPythonsys.exitbetterthanotherexitfunctions?PythonBitstring:ClassesandOtherExamples|Module Conclusion: Inconclusion,wecansay,Pythonitselfcannotsupporttheuseofmulticonstructorsforaclass.Itallowsdifferentalternativesdiscussedabove.However,constructoroverloadingand__init__definitionincurscertainproblems.Firstly,thereisnoclearindicationofwhatisrequiredwhilecreatingclassinstances.Also,therearedifferentcombinationsofinitializinganewinstancebypassingarguments.Thebestoutofthethreealternativesgivenisthusdecoratingwith@classmethoddecoratorsasmulticonstructors. However,ifyouhaveanydoubtsorquestionsdoletmeknowinthecommentsectionbelow.Iwilltrytohelpyouassoonaspossible. HappyPythoning! Subscribe Login Notifyof newfollow-upcomments newrepliestomycomments Label {} [+] Name* Email* Website Label {} [+] Name* Email* Website 0Comments InlineFeedbacks Viewallcomments AboutusPythonPoolisaplatformwhereyoucanlearnandbecomeanexpertineveryaspectofPythonprogramminglanguageaswellasinAI,ML,andDataScience. QuickLinks Algorithm Books Career Comparison DataScience Error Howto IDE&Editor Learning MachineLearning Matplotlib Module News Numpy OpenCV Pandas Programs Project PySpark Questions Review Software Tensorflow Tkinter Tutorials JoinusonTelegram wpDiscuzInsert
延伸文章資訊
- 1Multiple calls to __init__ during object initialization - CodeQL
However, standard object-oriented principles apply to Python classes using ... A class using mult...
- 2Ways to Achieve Multiple Constructors in Python
Python Methods calling from __init__ as Multiple Constructors
- 3python: multiple calls to __init__() on the same instance
Calling an __init__ method more than once during object initialization risks the object being inc...
- 4Python Multiple __init__ Functions - Answers for Devs
Python Multiple __init__ Functions. Can we define multiple constructor in Python? Unlike Java, yo...
- 5Python Class Constructor - Python __init__() Function
Python doesn't support multiple constructors, unlike other popular object-oriented programming la...