Python Class Constructor - Python __init__() Function

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

Python doesn't support multiple constructors, unlike other popular object-oriented programming languages such as Java. We can define multiple __init__() methods ... SkiptocontentPythonclassconstructorfunctionjobistoinitializetheinstanceoftheclass.Python__init__()istheconstructorfunctionfortheclassesinPython.Python__init__()FunctionSyntaxThe__init__()functionsyntaxis:def__init__(self,[arguments]) Thedefkeywordisusedtodefineitbecauseit’safunction.Thefirstargumentreferstothecurrentobject.Itbindstheinstancetotheinit()method.It’susuallynamed“self”tofollowthenamingconvention.YoucanreadmoreaboutitatPythonselfvariable.Theinit()methodargumentsareoptional.Wecandefineaconstructorwithanynumberofarguments.PythonClassConstructorExamplesLet’slookatsomeexamplesoftheconstructorfunctionindifferentscenarios.1.ClasswithNoConstructorWecancreateaclasswithoutanyconstructordefinition.Inthiscase,thesuperclassconstructoriscalledtoinitializetheinstanceoftheclass.TheobjectclassisthebaseofalltheclassesinPython.classData: pass d=Data() print(type(d))# Hereisanotherexampletoconfirmthatthesuperclassconstructoriscalledtoinitializetheinstanceofthesubclass.classBaseData: def__init__(self,i): print(f'BaseDataConstructorwithargument{i}') self.id=i classData(BaseData): pass d=Data(10) print(type(d)) Output:BaseDataConstructorwithargument10 2.SimpleConstructorwithNo-ArgumentsWecancreateaconstructorwithoutanyarguments.It’susefulforloggingpurposessuchaskeepingacountoftheinstancesoftheclass.classData1: count=0 def__init__(self): print('Data1Constructor') Data1.count+=1 d1=Data1() d2=Data1() print("Data1ObjectCount=",Data1.count) Output:Data1Constructor Data1Constructor Data1ObjectCount=2 3.ClassConstructorwithArgumentsMostofthetime,youwillfindtheconstructorfunctionwithsomearguments.Theseargumentsaregenerallyusedtoinitializetheinstancevariables.classData2: def__init__(self,i,n): print('Data2Constructor') self.id=i self.name=n d2=Data2(10,'Secret') print(f'DataIDis{d2.id}andNameis{d2.name}') Output:Data2Constructor DataIDis10andNameisSecret 4.ClassConstructorwithInheritanceclassPerson: def__init__(self,n): print('PersonConstructor') self.name=n classEmployee(Person): def__init__(self,i,n): print('EmployeeConstructor') super().__init__(n)#sameasPerson.__init__(self,n) self.id=i emp=Employee(99,'Pankaj') print(f'EmployeeIDis{emp.id}andNameis{emp.name}') Output:EmployeeConstructor PersonConstructor EmployeeIDis99andNameisPankaj Itisourresponsibilitytocallthesuperclassconstructor.Wecanusethesuper()functiontocallthesuperclassconstructorfunction.Wecanalsousethesuperclassnametocallitsinit()method.5.ConstructorChainingwithMultilevelInheritanceclassA: def__init__(self,a): print('AConstructor') self.var_a=a classB(A): def__init__(self,a,b): super().__init__(a) print('BConstructor') self.var_b=b classC(B): def__init__(self,a,b,c): super().__init__(a,b) print('CConstructor') self.var_c=c c_obj=C(1,2,3) print(f'c_objvar_a={c_obj.var_a},var_b={c_obj.var_b},var_c={c_obj.var_c}') Output:AConstructor BConstructor CConstructor c_objvar_a=1,var_b=2,var_c=3 6.ConstructorwithMultipleInheritanceWecan’tusesuper()toaccessallthesuperclassesincaseofmultipleinheritances.Thebetterapproachwouldbetocalltheconstructorfunctionofthesuperclassesusingtheirclassname.classA1: def__init__(self,a1): print('A1Constructor') self.var_a1=a1 classB1: def__init__(self,b1): print('B1Constructor') self.var_b1=b1 classC1(A1,B1): def__init__(self,a1,b1,c1): print('C1Constructor') A1.__init__(self,a1) B1.__init__(self,b1) self.var_c1=c1 c_obj=C1(1,2,3) print(f'c_objvar_a={c_obj.var_a1},var_b={c_obj.var_b1},var_c={c_obj.var_c1}') Output:C1Constructor A1Constructor B1Constructor c_objvar_a=1,var_b=2,var_c=3 PythonDoesn’tSupportMultipleConstructorsPythondoesn’tsupportmultipleconstructors,unlikeotherpopularobject-orientedprogramminglanguagessuchasJava.Wecandefinemultiple__init__()methodsbutthelastonewilloverridetheearlierdefinitions.classD: def__init__(self,x): print(f'Constructor1withargument{x}') #thiswilloverwritetheaboveconstructordefinition def__init__(self,x,y): print(f'Constructor1witharguments{x},{y}') d1=D(10,20)#Constructor1witharguments10,20 CanPython__init__()functionreturnsomething?Ifwetrytoreturnanon-Nonevaluefromthe__init__()function,itwillraiseTypeError.classData: def__init__(self,i): self.id=i returnTrue d=Data(10) Output:TypeError:__init__()shouldreturnNone,not'bool' IfwechangethereturnstatementtoreturnNonethenthecodewillworkwithoutanyexception.References:object__init__()functiondocs Postnavigation←PreviousPostNextPost→ Searchfor: RecentPosts ImportanceofRemediationinOpenSourceSecurity ThefunctoolsModuleinPython PythonicWayofWritingCode AreLaptopsPowerfulEnoughforProgramming? TypeHintingandAnnotationsinPython ImplementingHashMapsinPython UnderstandingTracebacksinPython wxPython:CreatingGUIswithPython DecodingDataProducts:WhyUseaDataMesh? Pipenv:TheNewPackagingToolForPythonFavoriteSitesGoLangTutorialsVM-HelpLinuxTutorialsMySQLTutorialsCodeForGeekMkyong



請為這篇文章評分?