Explaining the 'self' variable to a beginner - Stack Overflow
文章推薦指數: 80 %
I know conceptually what an object is, and that objects have methods. I even understand that in python, classes are objects! That's cool, I just don't know what ...
Lessthan10daystoRSVP!Virtuallyjoinusatourinauguralconference,everyoneiswelcome.
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
LearnmoreaboutCollectives
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
LearnmoreaboutTeams
Explainingthe'self'variabletoabeginner[duplicate]
AskQuestion
Asked
11years,1monthago
Modified
2years,6monthsago
Viewed
87ktimes
39
29
Thisquestionalreadyhasanswershere:
Whatisthepurposeofthe`self`parameter?Whyisitneeded?
(26answers)
Closed6yearsago.
I'mprettymuchignorantofOOPjargonandconcepts.Iknowconceptuallywhatanobjectis,andthatobjectshavemethods.Ievenunderstandthatinpython,classesareobjects!That'scool,Ijustdon'tknowwhatitmeans.Itisn'tclickingwithme.
I'mcurrentlytryingtounderstandafewdetailedanswersthatIthinkwillilluminatemyunderstandingofpython:
Whatdoesthe"yield"keyworddoinPython?
WhatisametaclassinPython?
Inthefirstanswer,theauthorusesthefollowingcodeasanexample:
>>>classBank():#let'screateabank,buildingATMs
...crisis=False
...defcreate_atm(self):
...whilenotself.crisis:
...yield"$100"
Idon'timmediatelygrokwhatselfispointingto.Thisisdefinitelyasymptomofnotunderstandingclasses,whichIwillworkonatsomepoint.Toclarify,in
>>>deffunc():
...foriinrange(3):
...printi
Iunderstandthatipointstoaniteminthelistrange(3)which,sinceitisinafunction,isn'tglobal.Butwhatdoesself"pointto"?
pythonoopclassscope
Share
Improvethisquestion
Follow
editedMar25,2020at22:30
martineau
115k2525goldbadges160160silverbadges283283bronzebadges
askedAug9,2011at0:18
jrhorn424jrhorn424
1,93322goldbadges2121silverbadges2626bronzebadges
3
9
selfisnotakeyword...
– JBernardo
Aug9,2011at0:21
4
thebankexampleisconfusingbecause"crisis"isaclassattribute,sothe4thlinemighthavebeenbetterwrittenwhilenotBank.crisis:.what'shappeningisthatselfispointingtotheobject,butsincetheobjectdoesn'thavea"crisis"attributepythonthenlooksattheclass.that'showyoumanageto"see"thecrisisattribute,eventhoughselfispointingtotheobject.
– andrewcooke
Aug9,2011at0:35
Thanks@JBernardo,fixedthetitle.
– jrhorn424
Aug10,2011at15:18
Addacomment
|
8Answers
8
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
98
I'lltrytoclearupsomeconfusionaboutclassesandobjectsforyoufirst.Letslookatthisblockofcode:
>>>classBank():#let'screateabank,buildingATMs
...crisis=False
...defcreate_atm(self):
...whilenotself.crisis:
...yield"$100"
Thecommentthereisabitdeceptive.Theabovecodedoesnot"create"abank.Itdefineswhatabankis.Abankissomethingwhichhasapropertycalledcrisis,andafunctioncreate_atm.That'swhattheabovecodesays.
Nowlet'sactuallycreateabank:
>>>x=Bank()
There,xisnowabank.xhasapropertycrisisandafunctioncreate_atm.Callingx.create_atm();inpythonisthesameascallingBank.create_atm(x);,sonowselfreferstox.Ifyouaddanotherbankcalledy,callingy.create_atm()willknowtolookaty'svalueofcrisis,notx'ssinceinthatfunctionselfreferstoy.
selfisjustanamingconvention,butitisverygoodtostickwithit.It'sstillworthpointingoutthatthecodeaboveisequivalentto:
>>>classBank():#let'screateabank,buildingATMs
...crisis=False
...defcreate_atm(thisbank):
...whilenotthisbank.crisis:
...yield"$100"
Share
Improvethisanswer
Follow
editedJul11,2014at14:23
answeredAug9,2011at0:35
PaulPaul
137k2626goldbadges270270silverbadges259259bronzebadges
7
18
Actually,whilebeginnersshouldn'tknoworcare,classesAREobjects(oftype'type')inPython.;)
– RussellBorogove
Aug9,2011at0:45
1
+1forgreatinsightonthecomment.Thisdidclearupconfusiononclasses.Ihadn'tfullyappreciatedthedifferencebetweenaclassandaninstance,anddidn'tknowyoucouldevencreateanobjectbyClass.method(obj).
– jrhorn424
Aug9,2011at15:42
1
Acceptedsince,whenIreadthisanswer,thingsstartedclicking.Otheranswerswereessentialtounderstanding,aswell!
– jrhorn424
Aug10,2011at15:29
1
Isn'tthiswrong?Lookingatthisexample:stackoverflow.com/a/475873/3402768.Becausecrisisdoesn'tuseselfintheinitializationitisaclassvariableandissharedbetweeninstances.Sobankxandycheckonthesamevalueofcrisis?!
– uitty400
Aug19,2016at9:31
1
x.create_atm();inpythonisthesameascallingBank.create_atm(x);Ifindthisaveryhelpfulanalogyactually
– MoteZart
Mar28,2019at23:54
|
Show2morecomments
19
Itmayhelpyoutothinkoftheobj.method(arg1,arg2)invocationsyntaxaspurelysyntacticsugarforcallingmethod(obj,arg1,arg2)(exceptthatmethodislookedupviaobj'stype,andisn'tglobal).
Ifyouviewitthatway,objisthefirstargumenttothefunction,whichtraditionallyisnamedselfintheparameterlist.(Youcan,infact,nameitsomethingelse,andyourcodewillworkcorrectly,butotherPythoncoderswillfrownatyou.)
Share
Improvethisanswer
Follow
answeredAug9,2011at0:21
C.K.YoungC.K.Young
215k4444goldbadges383383silverbadges426426bronzebadges
4
1
+1.Thisviewalsoexplainsthefoo()takesexactlynarguments,n+1givenWhenthecallerispassingnarguments,butshouldreallybepassingn-1arguments
– JohnLaRooy
Aug9,2011at4:07
2
Iwouldhavesaidthinkofitassugarfortype(obj).method(obj,arg1,arg2)whichavoidsthewoolinessoverthelookup.
– Duncan
Aug9,2011at8:46
So,@Chris,thismeansthateverytimeIdefineafunctioninmyclass,ifIwantthatfunctiontoactonaninstanceofthatclass,Ineedtohaveonemandatoryargumentcalledself?
– jrhorn424
Aug9,2011at15:40
3
@jrhorn424:Yes,anditmustbethefirstparameter.(Andifyoudon'twanttouseaninstanceoftheclass---ifit'sastaticmethod---then,inordertoavoidhavingtospecifythe(unused)selfparameter,youmustdecoratethatmethodwiththe@staticmethoddecorator.)
– C.K.Young
Aug9,2011at17:20
Addacomment
|
14
"self"istheinstanceobjectautomaticallypassedtotheclassinstance'smethodwhencalled,toidentifytheinstancethatcalledit."self"isusedtoaccessotherattributesormethodsoftheobjectfrominsidethemethod.(methodsarebasicallyjustfunctionsthatbelongtoaclass)
"self"doesnotneedtobeusedwhencallingamethodwhenyoualreadyhaveanavailableinstance.
Accessingthe"some_attribute"attributefrominsideamethod:
classMyClass(object):
some_attribute="hello"
defsome_method(self,some_string):
printself.some_attribute+""+some_string
Accessingthe"some_attribute"attributefromanexistinginstance:
>>>#createtheinstance
>>>inst=MyClass()
>>>
>>>#accessingtheattribute
>>>inst.some_attribute
"hello"
>>>
>>>#callingtheinstance'smethod
>>>inst.some_method("world")#Inadditionto"world",instis*automatically*passedhereasthefirstargumentto"some_method".
helloworld
>>>
Hereisalittlecodetodemonstratethatselfisthesameastheinstance:
>>>classMyClass(object):
>>>defwhoami(self,inst):
>>>printselfisinst
>>>
>>>local_instance=MyClass()
>>>local_instance.whoami(local_instance)
True
Asmentionedbyothers,it'snamed"self"byconvention,butitcouldbenamedanything.
Share
Improvethisanswer
Follow
answeredAug9,2011at1:55
monkutmonkut
40.2k2323goldbadges118118silverbadges148148bronzebadges
1
1
+1formakingitclearthatlocal_instanceispassedontothemethod,andthatmethodsarejustfunctionsthataredefinedinclasses.Thanks!
– jrhorn424
Aug10,2011at15:32
Addacomment
|
6
selfreferstothecurrentinstanceofBank.WhenyoucreateanewBank,andcallcreate_atmonit,selfwillbeimplicitlypassedbypython,andwillrefertothebankyoucreated.
Share
Improvethisanswer
Follow
answeredAug9,2011at0:23
recursiverecursive
81.9k3232goldbadges147147silverbadges236236bronzebadges
Addacomment
|
6
Idon'timmediatelygrokwhatselfispointingto.Thisisdefinitelyasymptomofnotunderstandingclasses,whichIwillworkonatsomepoint.
selfisanargumentpassedintothefunction.InPython,thisfirstargumentisimplicitlytheobjectthatthemethodwasinvokedon.Inotherwords:
classBar(object):
defsomeMethod(self):
returnself.field
bar=Bar()
bar.someMethod()
Bar.someMethod(bar)
Theselasttwolineshaveequivalentbehavior.(UnlessbarreferstoanobjectofasubclassofBar--thensomeMethod()mightrefertoadifferentfunctionobject.)
Notethatyoucannamethe"special"firstargumentanythingyouwant--selfisjustaconventionformethods.
Iunderstandthatipointstoaniteminthelistrange(3)which,sinceitisinafunction,isn'tglobal.Butwhatdoesself"pointto"?
Thenameselfdoesnotexistinthecontextofthatfunction.AttemptingtouseitwouldraiseaNameError.
Exampletranscript:
>>>classBar(object):
...defsomeMethod(self):
...returnself.field
...
>>>bar=Bar()
>>>bar.field="foo"
>>>bar.someMethod()
'foo'
>>>Bar.someMethod(bar)
'foo'
>>>deffn(i):
...returnself
...
>>>fn(0)
Traceback(mostrecentcalllast):
File"
延伸文章資訊
- 1Python Class Variables With Examples - PYnative
In Python, Class variables are declared when a class is being ... Access class variable inside in...
- 2Understanding Python self Variable with Examples - AskPython
Python self variable is used to bind the instance of the class to the instance method. We have to...
- 3Self variable - Python OOPs 03 - YouTube
- 4How to use self in Python – explained with examples
- 5Python's self - Python Morsels
self is the first method of every Python class