Explaining the 'self' variable to a beginner - Stack Overflow

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

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"",line1,in File"",line2,infn NameError:globalname'self'isnotdefined Share Improvethisanswer Follow editedAug9,2011at0:32 answeredAug9,2011at0:23 cdhowiecdhowie 149k2323goldbadges278278silverbadges290290bronzebadges 1 ithinkthisisthebestexplanationforbeginners! – MdSifatulIslam Jan18,2017at21:58 Addacomment  |  3 Thereason"self"isthere(byconvention)isthatwhenthePythonruntimeseesacalloftheformObject.Method(Param1,Param2),itcallsMethodwithparameters(Object,Param1,Param2).Soifyoucallthatfirstparameter"self",everyonewillknowwhatyouaretalkingabout. Thereasonyouhavetodothisisthesubjectofanotherquestion. Asfarasametaclass,it'ssomethingrarelyused.Youmightwanttolookat: http://python-history.blogspot.com/2009/04/metaclasses-and-extension-classes-aka.html,theoriginalauthorandcurrentBenevolentDictatorForLifeofPythonexplainswhatthisis,andhowitcametobe.Healsohasanicearticleonsomepossibleuses,butmostpeopleneverdirectlyuseitatall. Share Improvethisanswer Follow answeredAug9,2011at0:30 psrpsr 2,8401717silverbadges2222bronzebadges Addacomment  |  3 OneRubyist'sperspective(RubyismyfirstprogramminglanguagesoIapologizeforwhateveroversimplified,potentiallywrongabstractionsI'mabouttouse) asfarasIcantell,thedotoperator,forexample: os.path issuchthatosgetspassedintopath()asitsfirstvariable"invisibly" Itisasifos.pathisREALLYthis: path(os) IftherewereadaisychainI'dimaginethatthis: os.path.filename Wouldbesortoflikethisinreality*: filename(path(os)) Herecomestheoffensivepart Sowiththeselfvariableallthat'sdoingisallowingtheCLASSMETHOD(fromarubyistperspectivepython'instancemethods'appeartobeclassmethods...)toactasaninstancemethodbygettinganinstancepassedintoitasitsfirstvariable(viathe"sneaky"dotmethodabove)whichiscalledselfbyconvention.Wereselfnotaninstance c=ClassName() c.methodname buttheclassitself: ClassName.methodname theclasswouldgetpassedinratherthantheinstance. OK,alsoimportanttorememberisthatthe__init__methodiscalled"magic"bysome.Sodon'tworryaboutwhatgetspassedintogenerateanewinstance.Tobehonestitsprobablynil. Share Improvethisanswer Follow editedJul2,2014at16:22 answeredJul2,2014at16:16 boulder_rubyboulder_ruby 36.5k99goldbadges7171silverbadges9494bronzebadges Addacomment  |  2 selfreferstoaninstanceoftheclass. Share Improvethisanswer Follow answeredAug9,2011at0:21 MRABMRAB 19.9k55goldbadges3838silverbadges3131bronzebadges Addacomment  |  Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonoopclassscopeoraskyourownquestion. TheOverflowBlog IspenttwoyearstryingtodowhatBackstagedoesforfree Aserialentrepreneurfinallyembracesopensource(Ep.486) FeaturedonMeta PlannedmaintenancescheduledforWednesday,21September,00:30-03:00UTC... RecentColorContrastChangesandAccessibilityUpdates Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew... ShouldIexplainotherpeople'scode-onlyanswers? Linked 1274 Whatisthepurposeofthe`self`parameter?Whyisitneeded? 12253 Whatdoesthe"yield"keyworddo? 6952 WhataremetaclassesinPython? 87 Python-whyuse"self"inaclass? 0 Python:whytwoinstanceusethesamelist? 1 Whydofunctions/methodsinpythonneedselfasparameter? 2 Classvariables:"classlist"vs"classboolean" 1 ObjectOrientedexampleinPython 0 Whychangeclass'sattributesresultindifferentconsequences? 0 Whatistheactualuseofselfininitinpython? Seemorelinkedquestions Related 2181 WhenshouldIuse'self'over'$this'? 4140 Findingtheindexofaniteminalist 12253 Whatdoesthe"yield"keyworddo? 3597 HowdoIgetthecurrenttime? 4841 Accessingtheindexin'for'loops 5904 Whatisthedifferencebetween"let"and"var"? 3135 HowdoIpassavariablebyreference? 1274 Whatisthepurposeofthe`self`parameter?Whyisitneeded? 1815 IsthereareasonforC#'sreuseofthevariableinaforeach? HotNetworkQuestions HowlongaretheeventsofHalf-Life2in-universe? Crank-basedPowerMeterforShimanoSora Dowesay"abarofstaples"? Whatisthefunctionofthistoolofmyscissors? Howtoplayasadual-wieldingmonk? Advantagesofalawlicenseotherthantheabilitytopracticelaw lscommandline-wrapprevention Removetickmarksbutkeeplabelsfor3Dplot RobustwaytoresolveaDNSaddressinascript(IPv4(A)andIPv6(AAAA))? Canananimalhaveabodycoveredwith"hearing"hair? Whatdoesitmeanto"endupwithaDesmond"? Isthereanalgorithmforthegenusofaknot? Isitacrimeto"steal"yourownmoneyfromabank? DoesNECrequirejunctionboxestobeaccessiblewithouttools? ShouldIallowaPhDstudenttousefiguresofmyUndergraduatedissertationintheirPhDthesis? AsaPhDstudentintheoreticalphysics,whatfractionofmytime(ifany)shouldIspendonbackgroundmaterialratherthanmyresearchproblem? Inaircraftreliabilitymonitoringanalysis,whythecalculationofdefectrateisper1000FH? Canameteorshowerhaveaintervalgreaterthan1year? InwhichtournamentdidKarpovplayhisfirstmovewithwhitepiecesandofferadraw? CurrencyexchangerateinParis Dobasiclandcardsenterthebattlefieldtapped? Isitokaythatpartofthepowerjackisoutsidethedevice? Sci-fihorrorshortstoryaboutalienthatwantstobeeaten Whowerethetwolargehobbits? morehotquestions lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?