deleter decorator using Property in Python - Stack Overflow

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

I'm playing around with property in Python and I was wondering how this @propertyName.deleter decorator works. Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore deleterdecoratorusingPropertyinPython AskQuestion Asked 12years,3monthsago Modified 12years,3monthsago Viewed 13ktimes 16 2 I'mplayingaroundwithpropertyinPythonandIwaswonderinghowthis@propertyName.deleterdecoratorworks.I'mprobablymissingsomething,IcouldnotfindclearanswersbyGoogle. WhatIwouldliketoachieveiswhenthisdeleterbehavioriscalled,Icantriggerotheractions(e.g:usingmy3dapplicationSDK). Fornowjustasimpleprint()doesn'tseemtogettriggered. IsdeleterfiredwhenIdeletethepropertyusingdel(instance.property)? Otherwise,howcanIachievethis? classM(): def__init__(self): self._m=None @property defmmm(self): returnself._m @mmm.setter defmmm(self,val): self._m=val @mmm.deleter defmmm(self): print('deleting')#Notprinting del(self._m) if__name__=='__main__': i=M() i.mmm=150 print(i.mmm) del(i.mmm) print(i.mmm) Thankyouverymuch(: pythonpropertiesdecorator Share Follow askedDec16,2009at4:11 user111086user111086 Addacomment  |  2Answers 2 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 14 MakeManew-styleclass: classM(object): Seehttp://www.python.org/download/releases/2.2.3/descrintro/#property: Propertiesdonotworkforclassic classes,butyoudon'tgetaclear errorwhenyoutrythis.Yourget methodwillbecalled,soitappears towork,butuponattribute assignment,aclassicclassinstance willsimplysetthevalueinits dictwithoutcallingtheproperty'ssetmethod,andafterthat, theproperty'sgetmethodwon'tbe calledeither.(Youcouldoverride setattrtofixthis,butitwouldbeprohibitivelyexpensive.) Share Follow answeredDec16,2009at4:16 unutbuunutbu 765k160160goldbadges16791679silverbadges16011601bronzebadges 0 Addacomment  |  9 InPython3youWOULDseetheprint'sresult--andthenanAttributeErrorforthelastprint(because_mhasdisappeared).YoumaybeusingPython2.6,inwhichcaseyouneedtochangetheclassclausetoclassM(object):tomakeMnew-style,andthenyou'llgetthesamebehaviorasinPython3. Share Follow answeredDec16,2009at4:21 AlexMartelliAlexMartelli 803k161161goldbadges11911191silverbadges13651365bronzebadges 0 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 TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems GettingthroughaSOC2auditwithyournervesintact FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Related 6681 WhataremetaclassesinPython? 5128 HowcanIsafelycreateanesteddirectory? 7201 DoesPythonhaveaternaryconditionaloperator? 3504 HowtogetthecurrenttimeinPython 3614 Usingglobalvariablesinafunction 3250 HowdoIconcatenatetwolistsinPython? 2816 Manuallyraising(throwing)anexceptioninPython 3833 Iteratingoverdictionariesusing'for'loops 3591 DoesPythonhaveastring'contains'substringmethod? 1210 Howdoesthe@propertydecoratorworkinPython? HotNetworkQuestions Minussignnotaligningwithfraction RecreateMinecraft'slighting Willunevenspeedberoundedupordown? Howtogetamotorcycletoaskillstest HowcanIfacilitateafasterpaceofplay? WhydoesahypersonicmissileneedtocruiseEarthatlowaltitudebeforehittingitsmark? Howtomotivatestafftoattendapaidcertification? WhatisthegeographicallocationofPython(andotheropen-sourcesoftwareprojects)? Whyarerealphotonssomuchlessefficientincarryingmomentumthanvirtualphotons? Derivingtheapparentangularspeedofastar 1980spaperbackaboutamanwhotraveledonaspaceshipmadeofice WeirdpowerlinesforS-100,whyno5V? Meaningof"orwehaveheadphonesorwedon't,so..." HowdoyouexplainCanada'sTrudeau'spower-sharingagreementtoafive-year-old(American)? StopPipesFromPullingThroughTheWall HowWouldHumanoidsFormTheirOwnGems? Howdoestheprincipleofrelativityimplythatphotonclocksandmechanicalclocksexperiencetimedilationthesameway? WhydoesAgustínsay"miércoles"intheEncantomovie?Whatdoesitmean? Fallout4chemistryworkstation-backgroundimageusedforreflections Whatisagoodsoftwaretomaketechincaland/orschematicillustrationsaboutspace/orbitaldynamicstopics? Retainingambitiousemployeewithrareskillset Whatisaקאפיזי"ש? Cleverefandcaption-basedcommand-wrongreferences Whenandhowtoleaveafacultypositionforanewdepartment/universityorindustry morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?