Python Property

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

The Python property class ... The property() has the following parameters: ... The following uses the property() function to define the age property for the Person ... SkiptocontentHome»PythonOOP»PythonPropertySummary:inthistutorial,you’lllearnaboutthePythonpropertyclassandhowtouseittodefinepropertiesforaclass.IntroductiontoclasspropertiesThefollowingdefinesaPersonclassthathastwoattributesnameandage,andcreateanewinstanceofthePersonclass:classPerson: def__init__(self,name,age): self.name=name self.age=age john=Person('John',18)Codelanguage:Python(python)SinceageistheinstanceattributeofthePersonclass,youcanassignitanewvaluelikethis:john.age=19Codelanguage:Python(python)Thefollowingassignmentisalsotechnicallyvalid:john.age=-1Codelanguage:Python(python)However,theageissemanticallyincorrect.Toensurethattheageisnotzeroornegative,youusetheifstatementtoaddacheckasfollows:age=-1 ifage<=0: raiseValueError('Theagemustbepositive') else: john.age=ageCodelanguage:Python(python)Andyouneedtodothiseverytimeyouwanttoassignavaluetotheageattribute.Thisisrepetitiveanddifficulttomaintain.Toavoidthisrepetition,youcandefineapairofmethodscalledgetterandsetter.GetterandsetterThegetterandsettermethodsprovideaninterfaceforaccessinganinstanceattribute:ThegetterreturnsthevalueofanattributeThesettersetsanewvalueforanattributeInourexample,youcanmaketheageattributeprivate(byconvention)anddefineagetterandasettertomanipulatetheageattribute.ThefollowingshowsthenewPersonclasswithagetterandsetterfortheageattribute:classPerson: def__init__(self,name,age): self.name=name self.set_age(age) defset_age(self,age): ifage<=0: raiseValueError('Theagemustbepositive') self._age=age defget_age(self): returnself._ageCodelanguage:Python(python)Howitworks.InthePersonclass,theset_age()isthesetterandtheget_age()isthegetter.Byconventionthegetterandsetterhavethefollowingname:get_()andset_().Intheset_age()method,weraiseaValueErroriftheageislessthanorequaltozero.Otherwise,weassigntheageargumenttothe_ageattribute:defset_age(self,age): ifage<=0: raiseValueError('Theagemustbepositive') self._age=ageCodelanguage:Python(python)Theget_age()methodreturnsthevalueofthe_ageattribute:defget_age(self): returnself._ageCodelanguage:Python(python)Inthe__init__()method,wecalltheset_age()settermethodtoinitializethe_ageattribute:def__init__(self,name,age): self.name=name self.set_age(age)Codelanguage:Python(python)Thefollowingattemptstoassignaninvalidvaluetotheageattribute:john=Person('John',18) john.set_age(-19)Codelanguage:Python(python)AndPythonissuedaValueErrorasexpected.ValueError:TheagemustbepositiveCodelanguage:Python(python)Thiscodeworksjustfine.Butithasabackwardcompatibilityissue.SupposeyoureleasedthePersonclassforawhileandotherdevelopershavebeenalreadyusingit.Andnowyouaddthegetterandsetter,allthecodethatusesthePersonwon’tworkanymore.Todefineagetterandsettermethodwhileachievingbackwardcompatibility,youcanusetheproperty()class.ThePythonpropertyclassThepropertyclassreturnsapropertyobject.Theproperty()classhasthefollowingsyntax:property(fget=None,fset=None,fdel=None,doc=None)Codelanguage:Python(python)Theproperty()hasthefollowingparameters:fgetisafunctiontogetthevalueoftheattribute,orthegettermethod.fsetisafunctiontosetthevalueoftheattribute,orthesettermethod.fdelisafunctiontodeletetheattribute.docisadocstringi.e.,acomment.Thefollowingusestheproperty()functiontodefinetheagepropertyforthePersonclass.classPerson: def__init__(self,name,age): self.name=name self.age=age defset_age(self,age): ifage<=0: raiseValueError('Theagemustbepositive') self._age=age defget_age(self): returnself._age age=property(fget=get_age,fset=set_age)Codelanguage:Python(python)InthePersonclass,wecreateanewpropertyobjectbycallingtheproperty()andassignthepropertyobjecttotheageattribute.Notethattheageisaclassattribute,notaninstanceattribute.ThefollowingshowsthatthePerson.ageisapropertyobject:print(Person.age)Codelanguage:Python(python)Output:Codelanguage:Python(python)ThefollowingcreatesanewinstanceofthePersonclassandaccesstheageattribute:john=Person('John',18)Codelanguage:Python(python)Thejohn.__dict__storestheinstanceattributesofthejohnobject.Thefollowingshowsthecontentsofthejohn.__dict__:print(john.__dict__)Codelanguage:Python(python)Output:{'_age':18,'name':'John'}Codelanguage:Python(python)Asyoucanseeclearlyfromtheoutput,thejohn.__dict__doesn’thavetheageattribute.Thefollowingassignsavaluetotheageattributeofthejohnobject:john.age=19Codelanguage:Python(python)Inthiscase,Pythonlooksuptheageattributeinthejohn.__dict__first.BecausePythondoesn’tfindtheageattributeinthejohn.__dict__,it’llthenfindtheageattributeinthePerson.__dict__.ThePerson.__dict__storestheclassattributesofthePersonclass.ThefollowingshowsthecontentsofthePerson.__dict__:pprint(Person.__dict__)Codelanguage:Python(python)Output:mappingproxy({'__dict__':, '__doc__':None, '__init__':, '__module__':'__main__', '__weakref__':, 'age':, 'get_age':, 'set_age':})Codelanguage:Python(python)BecausePythonfindstheageattributeinthePerson.__dict__,it’llcalltheagepropertyobject.Whenyouassignavaluetotheageobject:john.age=19Codelanguage:Python(python)Pythonwillcallthefunctionassignedtothefsetargument,whichistheset_age().Similarly,whenyoureadfromtheagepropertyobject,Pythonwillexecutethefunctionassignedtothefgetargument,whichistheget_age()method.Byusingtheproperty()class,wecanaddapropertytoaclasswhilemaintainingbackwardcompatibility.Inpractice,youwilldefinetheattributesfirst.Later,youcanaddthepropertytotheclassifneeded.Puttingitalltogether.frompprintimportpprint classPerson: def__init__(self,name,age): self.name=name self.age=age defset_age(self,age): ifage<=0: raiseValueError('Theagemustbepositive') self._age=age defget_age(self): returnself._age age=property(fget=get_age,fset=set_age) print(Person.age) john=Person('John',18) pprint(john.__dict__) john.age=19 pprint(Person.__dict__)Codelanguage:Python(python)SummaryUsethePythonproperty()classtodefineapropertyforaclass.PreviouslyPythonOperatorOverloadingUpNextPythonPropertyDecoratorSearchfor:Classes&ObjectsSpecialMethodsPropertySingleInheritanceEnumerationsSOLIDPrinciplesMultipleInheritanceDescriptorsMetaProgrammingExceptions



請為這篇文章評分?