Use of the __init__() Function in Python - Linux Hint

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

Here, the __init__() function will take two argument values at the time of the object creation that will be used to initialize two class variables, and another ... Pythonsupportsbothstructuredandobject-orientedprogramming.Theclassandobjectareusedtoimplementobject-orientedprogramming.Theclassdefinesthepropertiesoftheobject.Theconstructormethodisusedinobject-orientedprogrammingtodeclare,initializeandmanipulatetheobject,andthismethodiscalledautomaticallywhenanobjectoftheclassiscreated.The__init__()functionworksliketheconstructormethodinPythonanditisdeclaredinsidetheclass. Syntax: Thesyntaxofthe__init__()functionisgivenbelow. __init__(self,[arguments]) Thefirstargumentofthefunctionisusedtorefertothecurrentobjectoftheclass.Theotherargumentsofthisfunctionareoptional.Zeroormoreargumentscanbeusedafterthefirstargumenttoinitializetheclassvariables.Differentusesofthe__init__()functionhavebeeninthenextpartofthetutorial. Example-1:UseofaConstructorWithoutAnyArgument CreateaPythonfilewiththefollowingscripttodefineaconstructormethodwithoutanyargumentbyusing__init__()function.ThisfunctionwillbecalledwhentheobjectoftheTestClasswillbecreated. #Declareaclasswithparameterlessconstructor classTestClass: #Declareconstructormethod def__init__(self): #Printasimplemessage print('Constructormethodhasbeencalled.') #Createobjectoftheclass object=TestClass() Output: Thefollowingoutputwillappearafterexecutingtheabovescript.The__init__()functionhasbeencalledwhentheobjectoftheclasswascreated,andthemessagefromthe__init__()function,‘Constructormethodhasbeencalled.’hasbeenprinted. Example-2:UseofaConstructorwithArguments CreateaPythonfilewiththefollowingscripttodefineaconstructormethodwithanargumentbyusingthe__init__()function.TwoobjectshavebeencreatedfortheTestClassclassinthescript.So,the__init__()functionwillbecalledtwotimesandinitializethenamevariablewiththevaluepassedtothefunctionatthetimeoftheobjectcreation. #Declareaclasswithaparameterizedconstructor classTestClass: #Declareconstructormethodwithoneargument def__init__(self,name): #Printasimplemessage print('Constructormethodhasbeencalled.') #Initializedtheclassvariable self.name=name #Createobjectoftheclass object1=TestClass('MirAbbas') print('Welcome,',object1.name) #Createanotherobjectoftheclass object2=TestClass('NilaChowdhury') print('Welcome,',object1.name) print('Welcome,',object2.name) Output: Thefollowingoutputwillappearafterexecutingtheabovescript.Thefirstobjecthasbeencreatedwiththevalue,‘MirAbbas’,andthesecondobjecthasbeencreatedwiththevalue,‘NilaChowdhury’.Theoutputshowsthatthesecondobjectcreatesacloneofthefirstobject.So,thepropertyvalueofthefirstobjectdidn’toverwritebythesecondobject. Example-3:UseofaConstructorwithAnotherMethod CreateaPythonfilewiththefollowingscriptwhereaconstructormethodhasbeendeclaredwiththeothermethod.Here,the__init__()functionwilltaketwoargumentvaluesatthetimeoftheobjectcreationthatwillbeusedtoinitializetwoclassvariables,andanothermethodoftheclasswillbecalledtoprintthevaluesoftheclassvariables. #Declareaclasswithparameterizedconstructor classTestClass: #Declareconstructormethodwithoneargument def__init__(self,name,profession): #Printasimplemessage print('Constructormethodhasbeencalled.') #Initializedtheclassvariables self.name=name self.profession=profession #Callanothermethod self.display_info() #Defineanothermethodoftheclass defdisplay_info(self): print("Theprofessionof",self.name,"is",self.profession) #Createobjectoftheclass object=TestClass('KabirHossain','CEO') Output: Thefollowingoutputwillappearafterexecutingtheabovescript.Twoclassvariableshavebeeninitializedwiththevalues,‘KabirHossain’and‘CEO’atthetimeoftheobjectcreationandthesevalueshavebeenprinted. Example-4:UseofaConstructorwithInheritance CreateaPythonfilewiththefollowingscriptwhereaconstructormethodhasbeenimplementedwiththefeatureofinheritance.The__init__()functionhasbeendefinedforboththeparentclassandchildclasshere.Thedisplay()methodhasbeendefinedalsoforboththeparentandchildclasses.The__init__()functionoftheparentclasshasoneargumentandthechildclasshasthreearguments. #Declaretheparentclass classParentClass: def__init__(self,name): print("Theparentconstructorhasbeencalled.\n") self.name=name defdisplay(self): print("Name:",self.name) #Declarethechildclass classChildClass(ParentClass): def__init__(self,name,post,salary): #Callconstructoroftheparentclass ParentClass.__init__(self,name) print("Thechildconstructorhasbeencalled.\n") self.post=post self.salary=salary defdisplay(self): print("Name:",self.name) print("Post:",self.post) print("Salary:",self.salary) #Createobjectoftheparentclass object1=ParentClass("TanvirHossain") object1.display() #Createobjectofthechildclass object2=ChildClass("FarheenHasan",'CEO',700000) object2.display() Output: Thefollowingoutputwillappearafterexecutingtheabovescript. Example-5:UseofaConstructorwithMultipleInheritance CreateaPythonfilewiththefollowingscriptwherethechildclasshasbeencreatedfromtwoparentclassesandthe__init__()functionhasbeendefinedforthesethreeclasses.Thechildclasshasanothermethodnameddisplay(),toprintthevaluesoftheclassvariables. #Declaretheparentclass classParentClass1: def__init__(self,name,email,contact_no): print("Theparentconstructorhasbeencalled.") self.name=name self.email=email self.contact_no=contact_no #Declaretheparentclass classParentClass2: def__init__(self,department,post): print("Anotherparentconstructorhasbeencalled.") self.department=department self.post=post #Declarethechildclass classChildClass(ParentClass1,ParentClass2): def__init__(self,name,email,contact_no,department,post,salary): #Callconstructoroftheparentclass ParentClass1.__init__(self,name,email,contact_no) #Callconstructorofanotherparentclass ParentClass2.__init__(self,department,post) print("Thechildconstructorhasbeencalled.\n") self.salary=salary defdisplay(self): print("Name:",self.name) print("Email:",self.email) print("ContactNo:",self.contact_no) print("Department:",self.department) print("Post:",self.post) print("Salary:",self.salary) #Createobjectofthechildclass object=ChildClass('FarhanAkter','[email protected]','8801937894567','HR','Manager',500000) #Callthedisplaymethod object.display() Output: Thefollowingoutputwillappearafterexecutingtheabovescript. Conclusion Thewaysofusingthe__init__()functioninPythonhavebeenshowninthistutorialbyusingsimpleexamplesforhelpingthePythonuserstoknowthepurposesofusingthisfunctionproperly. Abouttheauthor FahmidaYesmin Iamatrainerofwebprogrammingcourses.IliketowritearticleortutorialonvariousITtopics.IhaveaYouTubechannelwheremanytypesoftutorialsbasedonUbuntu,Windows,Word,Excel,WordPress,Magento,Laraveletc.arepublished:Tutorials4uHelp. Viewallposts RELATEDLINUXHINTPOSTS PandasVlookupPandasCheckVersionPandastoHTMLPandasSeriesFilterPandasRegexPandasReadTSVPythonCommandLineParsingTutorial



請為這篇文章評分?