self is the first method of every Python class
Articles
Screencasts
Exercises
Courses
Pastebin
Gift
/
SignUp
SignIn
Watchasvideo
03:28
Showcaptions
Autoplay
Auto-expand
Signintochangeyoursettings
SignintoyourPythonMorselsaccounttosaveyourscreencastsettings.
Don'thaveanaccountyet?Signuphere.
WhenyoudefineaclassinPython,you'llseeselfeverywhere.
Whatisselfandwhyisiteverywhere?
APythonclasswithselfineachmethod
ThebelowPointhasthreemethods:a__init__method,anis_originmethod,andamove_tomethod.
classPoint:
def__init__(self,x,y,z):
self.move_to(x,y,z)
defis_origin(self):
returnself.x==self.y==self.z==0
defmove_to(self,x,y,z):
self.x,self.y,self.z=x,y,z
Wecanmakeaninstanceofthisclass,bycallingit.
Wecanaccessattributesandcancallmethodsonthisclassinstance:
>>>p=Point(1,2,3)
>>>p.x
1
>>>p.is_origin()
False
>>>
Doweneedthatselfargument?
EachofthemethodsinourPointclassacceptsselfasitsfirstargument.
Whatdoyouthinkwillhappen,ifwedeletethatselfargument?
classPoint:
def__init__(x,y,z):
self.move_to(x,y,z)
defis_origin():
returnself.x==self.y==self.z==0
defmove_to(x,y,z):
self.x,self.y,self.z=x,y,z
NowwhenwecallthePointclasstomakeanewPointobject,we'llseeanerror:
>>>p=Point(1,2,3)
Traceback(mostrecentcalllast):
File"",line1,in
TypeError:__init__()takes3positionalargumentsbut4weregiven
>>>
Theerrorsays__init__(ourinitializermethod)takesthreepositionalarguments,butfourweregiven.
WeonlypassedthreeargumentsintoourPointclass;itgotfourargumentsbecauseselfwaspassedinasthefirstargument(beforethethreewespecified).
Sowhetheryoulikeitornot,thefirstargumenttoeveryoneofyourmethodsisgoingtobeself,whichmeansweneedtocapturethisselfthingthat'spassedinasthefirstargument.
Whatisself?
Sowhatisself?
Let'stemporarilychangeouris_originmethodheretoreturntheidofself:
defis_origin(self):
returnid(self)
Python'sidfunctionreturnsanumberrepresentingthememorylocationofaparticularobject.
Ifwecalltheis_originfunction,wegetanumber.
>>>p=Point(1,2,3)
>>>p.is_origin()
139775673938080
Ifwelookattheidofthepvariablewemade,we'regoingtogetthesamenumber:
>>>id(p)
139775673938080
ThatvariableppointstoaPointobject(remembervariablesarepointersinPython).
Thatselfvariableinourmethodcallpointstothesameexactobject.
Soselfisreallyjustavariablethatpointstotheinstanceofourclassthatwe'recurrentlyworkingwith.
Butwhatdoesselfmean?Couldwerenameit?
Whatifwetakeselfeverywhereinthecodeandchangeittothis?
classPoint:
def__init__(this,x,y,z):
this.move_to(x,y,z)
defis_origin(this):
returnthis.x==this.y==this.z==0
defmove_to(this,x,y,z):
this.x,this.y,this.z=x,y,z
Wouldourcodestillwork?
IfwemakeanewPointobjectagain,we'llseethatweeverythingworksasitdidbefore:wecanstillaccessattributesandwecanstillcallmethods:
>>>p=Point(1,2,3)
>>>p.x
1
>>>p.is_origin()
False
FromPython'sperspective,itdoesn'tactuallymatter,whatyoucallself.
Youjusthavetoacceptthattheinstanceofyourclasswillbepassedinasthefirstargument.
Theselfvariableisjustaverystrongconvention,youshouldcallitself(otherwiseotherPythonprogrammerswillbeconfusedwhenreadingyourcode)butyou'reallowedtocallitsomethingelse.
selfisthefirstmethodofeveryPythonclass
WhenPythoncallsamethodinyourclass,itwillpassintheactualinstanceofthatclassthatyou'reworkingwithasthefirstargument.
Someprogramminglanguagesusethewordthistorepresentthatinstance,butinPythonweusethewordself.
WhenyoudefineaclassinPython,everymethodthatyoudefine,mustacceptthatinstanceasitsfirstargument(calledselfbyconvention).
Theselfvariablepointstotheinstanceoftheclassthatyou'reworkingwith.
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:28
TableofContents
NextUp
03:09
__init__inPython
The__init__methodisusedtoinitializeaclass.Theinitializermethodacceptsself(theclassinstance)alongwithanyargumentstheclassacceptsandthenperformsinitializationsteps.