Calling a class function inside of __init__ - Stack Overflow

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

Is there a way to call a class function from within __init__ of that class? Or am I thinking about this the wrong way? python · class · Share. 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 Callingaclassfunctioninsideof__init__ AskQuestion Asked 9years,11monthsago Modified 1year,2monthsago Viewed 244ktimes 199 36 I'mwritingsomecodethattakesafilename,opensthefile,andparsesoutsomedata.I'dliketodothisinaclass.Thefollowingcodeworks: classMyClass(): def__init__(self,filename): self.filename=filename self.stat1=None self.stat2=None self.stat3=None self.stat4=None self.stat5=None defparse_file(): #dosomeparsing self.stat1=result_from_parse1 self.stat2=result_from_parse2 self.stat3=result_from_parse3 self.stat4=result_from_parse4 self.stat5=result_from_parse5 parse_file() Butitinvolvesmeputtingalloftheparsingmachineryinthescopeofthe__init__functionformyclass.Thatlooksfinenowforthissimplifiedcode,butthefunctionparse_filehasquiteafewlevelsofindentionaswell.I'dprefertodefinethefunctionparse_file()asaclassfunctionlikebelow: classMyClass(): def__init__(self,filename): self.filename=filename self.stat1=None self.stat2=None self.stat3=None self.stat4=None self.stat5=None parse_file() defparse_file(): #dosomeparsing self.stat1=result_from_parse1 self.stat2=result_from_parse2 self.stat3=result_from_parse3 self.stat4=result_from_parse4 self.stat5=result_from_parse5 Ofcoursethiscodedoesn'tworkbecausethefunctionparse_file()isnotwithinthescopeofthe__init__function.Isthereawaytocallaclassfunctionfromwithin__init__ofthatclass?OramIthinkingaboutthisthewrongway? pythonclass Share Improvethisquestion Follow editedOct16,2015at5:08 StefanvandenAkker 6,36977goldbadges4444silverbadges6363bronzebadges askedSep28,2012at19:40 PythonJinPythonJin 3,79444goldbadges3434silverbadges4040bronzebadges 1 2 Isthereanyreasonthecodeexampleneedsfiveversionsof"stat"?Itwouldmakeiteasiertoreadiftherewouldbeonlyone. – 465b Apr29,2020at15:23 Addacomment  |  6Answers 6 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 279 Callthefunctioninthisway: self.parse_file() Youalsoneedtodefineyourparse_file()functionlikethis: defparse_file(self): Theparse_filemethodhastobeboundtoanobjectuponcallingit(becauseit'snotastaticmethod).Thisisdonebycallingthefunctiononaninstanceoftheobject,inyourcasetheinstanceisself. Share Improvethisanswer Follow editedJul14,2021at23:43 answeredSep28,2012at19:45 LewisDiamondLewisDiamond 21.2k22goldbadges2121silverbadges3030bronzebadges 1 Yes!ThiswasexactlywhatIwaslookingfor.Thankyou! – PythonJin Sep28,2012at19:56 Addacomment  |  52 IfI'mnotwrong,bothfunctionsarepartofyourclass,youshoulduseitlikethis: classMyClass(): def__init__(self,filename): self.filename=filename self.stat1=None self.stat2=None self.stat3=None self.stat4=None self.stat5=None self.parse_file() defparse_file(self): #dosomeparsing self.stat1=result_from_parse1 self.stat2=result_from_parse2 self.stat3=result_from_parse3 self.stat4=result_from_parse4 self.stat5=result_from_parse5 replaceyourline: parse_file() with: self.parse_file() Share Improvethisanswer Follow editedSep28,2012at20:05 PaoloMoretti 52.2k2222goldbadges100100silverbadges9292bronzebadges answeredSep28,2012at19:45 ParitoshSinghParitoshSingh 6,09855goldbadges3636silverbadges5656bronzebadges 5 Couldyouexplainwhyitmustbeusedself.parse_file()andnotparse_file()? – ivanleoncz Aug8,2017at4:32 @paritoshsinghshoulddefparse_file(self):notbenestedunderthe__init__functionsothatyoudon'thaveapartiallyinitialisedobject? – ron_g Apr23,2018at19:19 @ivanleonczAsparse_fileisinstancemethod,weneedtousereferenceobjecttocallsame. – ParitoshSingh May6,2018at2:14 @rongIfthiscodeisvenerableandyoudon'twanttoallowsettingparsefilefromoutside,yesitshouldbenested. – ParitoshSingh May6,2018at2:24 Considerusingstaticmethodsprogramiz.com/python-programming/methods/built-in/staticmethod – SandeshGhanta Dec29,2020at13:35 Addacomment  |  16 Howabout: classMyClass(object): def__init__(self,filename): self.filename=filename self.stats=parse_file(filename) defparse_file(filename): #dosomeparsing returnresults_from_parse Bytheway,ifyouhavevariablesnamedstat1,stat2,etc.,thesituationisbeggingforatuple: stats=(...). Soletparse_filereturnatuple,andstorethetuplein self.stats. Then,forexample,youcanaccesswhatusedtobecalledstat3withself.stats[2]. Share Improvethisanswer Follow answeredSep28,2012at19:45 unutbuunutbu 796k170170goldbadges17201720silverbadges16221622bronzebadges 2 Iagree,Ijustputtheself.stat1throughself.stat5intheretoshowthatthereweresomeclassvariablesthatIwasassigningto.IntheactualcodeIhaveamoreelegantsolution. – PythonJin Sep28,2012at19:58 HowshouldthisbealteredifIwanttotheparse_filefunctiontobeamethodoftheMyClassobject.Wherewouldselfbenecessary? – n1k31t4 Jul1,2018at13:25 Addacomment  |  1 Youmustdeclareparse_filelikethis;defparse_file(self).The"self"parameterisahiddenparameterinmostlanguages,butnotinpython.Youmustaddittothedefinitionofallthatmethodsthatbelongtoaclass. Thenyoucancallthefunctionfromanymethodinsidetheclassusingself.parse_file yourfinalprogramisgoingtolooklikethis: classMyClass(): def__init__(self,filename): self.filename=filename self.stat1=None self.stat2=None self.stat3=None self.stat4=None self.stat5=None self.parse_file() defparse_file(self): #dosomeparsing self.stat1=result_from_parse1 self.stat2=result_from_parse2 self.stat3=result_from_parse3 self.stat4=result_from_parse4 self.stat5=result_from_parse5 Share Improvethisanswer Follow answeredSep28,2012at19:47 IonutHulubIonutHulub 5,92755goldbadges2626silverbadges5353bronzebadges Addacomment  |  0 Inparse_file,taketheselfargument(justlikein__init__).Ifthere'sanyothercontextyouneedthenjustpassitasadditionalargumentsasusual. Share Improvethisanswer Follow answeredSep28,2012at19:47 TeoKlestrupRöijezonTeoKlestrupRöijezon 4,91733goldbadges2626silverbadges3636bronzebadges Addacomment  |  -16 Ithinkthatyourproblemisactuallywithnotcorrectlyindentinginitfunction.Itshouldbelikethis classMyClass(): def__init__(self,filename): pass defparse_file(): pass Share Improvethisanswer Follow answeredSep28,2012at19:44 ZedZed 5,3551010goldbadges4040silverbadges7777bronzebadges 3 1 Neitherisyourcode.Unlessyouputthe@staticmethoddecoratorontopofparse_file – rantanplan Sep28,2012at19:46 atleastaddthemissingselfinyourparse_filemethod. – rantanplan Sep28,2012at19:49 Oops,sorrythereshouldhavebeenanextralayerofindentingunderthe"classMyClass():"line.I'vefixeditabove,butthequestionremainsthesame. – PythonJin Sep28,2012at19:55 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonclassoraskyourownquestion. TheOverflowBlog IspenttwoyearstryingtodowhatBackstagedoesforfree Aserialentrepreneurfinallyembracesopensource(Ep.486) FeaturedonMeta PlannedmaintenancescheduledforWednesday,21September,00:30-03:00UTC... RecentColorContrastChangesandAccessibilityUpdates Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew... ShouldIexplainotherpeople'scode-onlyanswers? Visitchat Linked 1 Whyclassmethodscalledonothermethods,shouldbecalledwith'self'? 0 Defininginstancevariablesusingfunctionsandinstancemethodsin__init__ -2 Callingamethodfromaconstructorinpython 0 Runandreturnvalueofclassfunctioninside__init__PythonClassConstructor 0 Pythonclassdatabaseconstructor 1 __init__methodexception-NameError:name'setShiftNum'isnotdefined Related 2277 Callingafunctionofamodulebyusingitsname(astring) 2403 StaticclassvariablesandmethodsinPython 3737 Usingglobalvariablesinafunction 3334 Whatis__init__.pyfor? 1836 Gettingtheclassnameofaninstance 3052 HowdoImakefunctiondecoratorsandchainthemtogether? 1274 Whatisthepurposeofthe`self`parameter?Whyisitneeded? 730 Whatisthedifferencebetween__init__and__call__? 1760 Whatdoes"Couldnotfindorloadmainclass"mean? HotNetworkQuestions Whyissendingtroopsdifferentfromsendingmilitaryequipment? SciencefictionshortstoryinwhichEinsteinisclonedbutshowsnointerestinmuchexceptplayinghisviolin Howtomakedefinedlabelsontopoftheedgeinagraphwithtikz? Numbersvs.Strings:Languagefitnesschallenge RobustwaytoresolveaDNSaddressinascript(IPv4(A)andIPv6(AAAA))? Printall"balanced"sequencesof'A'and'B' IntheRoEforapentest,doyouincludealistofalltools? WhyisloadratedinkW? Paladinfightingstyleblindfightinganddruidabilitywildshapeworkingtogether? Canyouuseyourbonusactiontomove,butnotattackwith,aspiritualweapon? Sci-fihorrorshortstoryaboutalienthatwantstobeeaten DoesNECrequirejunctionboxestobeaccessiblewithouttools? Dowesay"abarofstaples"? Whatexactlyismeantbyisotropicandanisotropicwithwordvectors Chessetiquette:Carlsenwithdrawingfromthetournament Iamlookingforaword(anounpreferablybutanadjectivewouldsuffice)thatdenotesapersonthatknowinglyallowsanothertousethemregularly Howtopreventhumansfrombeingkilledbyaliendiseases? Whatisthefunctionofthistoolofmyscissors? CanyoutraveltoIrelandwithanUK+SchengenVisa(ifyouareIndianandaretravellingfromAustria)? Does'invasion'implytheactionisunjust? Dobasiclandcardsenterthebattlefieldtapped? EachhaveorHaveeach lscommandline-wrapprevention Whatisatuneorsongcalledthatisrecurrentlyusedsopeoplestarttoassociatethetuneorsongwiththatwhatitisusedwith? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?