The __init__ method is used to initialize a class. The initializer method accepts self (the class instance) along with any arguments the class accepts and ...
Articles
Screencasts
Exercises
Courses
Pastebin
Gift
/
SignUp
SignIn
Watchasvideo
03:09
Showcaptions
Autoplay
Auto-expand
Signintochangeyoursettings
SignintoyourPythonMorselsaccounttosaveyourscreencastsettings.
Don'thaveanaccountyet?Signuphere.
Let'stalkaboutthe__init__methodinPython.
ApointlessPointclass
Here'saclasscalledPoint:
classPoint:
"""2-dimensionalpoint."""
Wecanconstructanewinstanceofthisclassbycallingit:
>>>p=Point()
>>>p
WehaveaPointobjectatthispoint,butthisPointobjectreallyhasnopointbecauseithasnofunctionality(itdoesn'tstoreanyusefuldataorhaveanymethods).
WecouldmanuallyaddattributestoPointobjectstostoresomedataonthem:
>>>p.x=1
>>>p.y=2
>>>p.x
1
Butdoingsowouldbealittlesilly.
Itwouldbebetterifwecouldsomehowcallthisclasswithargumentstostoreattributesautomatically.
Theinitializermethod
Currently,ifwetrytocallthisclasswitharguments,we'llseeanerror:
>>>p=Point(1,2)
Traceback(mostrecentcalllast):
File"",line1,in
TypeError:Point()takesnoarguments
>>>
Inordertoacceptarguments,weneedtodefinea__init__methodinourclass.
def__init__(self,x,y):
self.x=x
self.y=y
Thefirstargumentinour__init__methodwillalwaysbeself(justlikeprettymucheveryothermethod).
Afterthatweneedtodeclareanyargumentswewantourclasstoaccept.
Themainthingyou'llprettymuchalwaysseeina__init__method,isassigningtoattributes.
ThisisournewPointclass
classPoint:
"""2-dimensionalpoint."""
def__init__(self,x,y):
self.x=x
self.y=y
Ifwecallitlikebeforewithoutanyarguments,we'llseeanerrorbecausethisclassnowrequirestwoarguments,xandy:
>>>p=Point()
Traceback(mostrecentcalllast):
File"",line1,in
TypeError:__init__()missing2requiredpositionalarguments:'x'and'y'
WeneedtogiveourPointclasstwoargumentsinordertogetanewinstanceofthisclass:
>>>p=Point(1,2)
ThisPointobjectnowhasanxattributeandayattribute:
>>>p.x
1
>>>p.y
2
Thatmeansour__init__methodwascalled!
Pythoncalls__init__wheneveraclassiscalled
Wheneveryoucallaclass,Pythonwillconstructanewinstanceofthatclass,andthencallthatclass'__init__method,passinginthenewlyconstructedinstanceasthefirstargument(self).
Unlikemanyprogramminglanguages,__init__isn'tcalledthe"constructormethod".
Python's__init__methodiscalledtheinitializermethod.
Theinitializermethodinitializesournewclassinstance.
Sobythepointthattheinitializermethodiscalledtheclassinstancehasalreadybeenconstructed.
Summary
WhenyoumakeanewclassinPythonthefirstmethodyou'lllikelymakeisthe__init__method.
The__init__methodallowsyoutoacceptargumentstoyourclass.
Moreimportantly,the__init__methodallowsyoutoassigninitialvaluestovariousattributesonyourclassinstances.
Series:Classes
Classesareawaytobundlefunctionalityandstatetogether.
Theterms"type"and"class"areinterchangeable:list,dict,tuple,int,str,set,andboolareallclasses.
You'llcertainlyusequiteafewclassesinPython(remembertypesareclasses)butyoumaynotneedtocreateyourownoften.
TotrackyourprogressonthisPythonMorselstopictrail,signinorsignup.
0%
Whatisaclass?
04:34
Classesareeverywhere
03:14
Python'sself
03:28
__init__inPython
03:09
DocstringsinPython
04:43
Inheritingoneclassfromanother
04:08
AttributesareeverywhereinPython
02:30
Methodsarejustfunctionsattachedtoclasses
05:02
Whereareattributesstored?
03:07
Howattributelookupsandassignmentswork
03:35
WheredoesPythonlookformethods?
03:22
Restrictingclassattributeswith__slots__
04:17
Classmethods
03:47
Staticmethods
02:44
WhatcomesafterIntrotoPython?
IntrotoPythoncoursesoftenskipoversomefundamentalPythonconcepts.
SignupbelowandI'llexplainconceptsthatnewPythonprogrammersoftenoverlook.
Website
SignupforPythonConceptsBeyondtheBasics
✕
↑
ConceptsBeyondIntrotoPython
IntrotoPythoncoursesoftenskipoversomefundamentalPythonconcepts.
SignupbelowandI'llshareideasnewPythonistasoftenoverlook.
Website
Watchasvideo
03:09
TableofContents
NextUp
04:43
DocstringsinPython
InPythonwepreferdocstringstodocumentourcoderatherthanjustcomments.Docstringsmustbetheveryfirststatementintheirfunction,class,ormodule.Python'shelpfunctionusesthese.