Python Property Decorator

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

Introduction to the Python property decorator ... The property accepts a getter and returns a property object. ... So to get the age of a Person object, you can use ... SkiptocontentHome»PythonOOP»PythonPropertyDecoratorSummary:inthistutorial,you’lllearnaboutPythonpropertydecorator(@property)andmoreimportantlyhowitworks.IntroductiontothePythonpropertydecoratorIntheprevioustutorial,youlearnedhowtousethepropertyclasstoaddapropertytoaclass.Here’sthesyntaxofthepropertyclass:classproperty(fget=None,fset=None,fdel=None,doc=None)Codelanguage:Python(python)ThefollowingdefinesaPersonclasswithtwoattributesnameandage:classPerson: def__init__(self,name,age): self.name=name self.age=ageCodelanguage:Python(python)Todefineagetterfortheageattribute,youusethepropertyclasslikethis:classPerson: def__init__(self,name,age): self.name=name self._age=age defget_age(self): returnself._age age=property(fget=get_age)Codelanguage:Python(python)Thepropertyacceptsagetterandreturnsapropertyobject.ThefollowingcreatesaninstanceofthePersonclassandgetthevalueoftheagepropertyviatheinstance:john=Person('John',25) print(john.age)Codelanguage:Python(python)Output:25Codelanguage:Python(python)Also,youcancalltheget_age()methodofthePersonobjectdirectlylikethis:print(john.get_age())Codelanguage:Python(python)SotogettheageofaPersonobject,youcanuseeithertheagepropertyortheget_age()method.Thiscreatesanunnecessaryredundancy.Toavoidthisredundancy,youcanrenametheget_age()methodtotheage()methodlikethis:classPerson: def__init__(self,name,age): self.name=name self._age=age defage(self): returnself._age age=property(fget=age)Codelanguage:Python(python)Theproperty()acceptsacallable(age)andreturnsacallable.Therefore,itisadecorator.Therefore,youcanusethe@propertydecoratortodecoratetheage()methodasfollows:classPerson: def__init__(self,name,age): self.name=name self._age=age @property defage(self): returnself._age Codelanguage:Python(python)Sobyusingthe@propertydecorator,youcansimplifythepropertydefinitionforaclass.SetterdecoratorsThefollowingaddsasettermethod(set_age)toassignavalueto_ageattributetothePersonclass:classPerson: def__init__(self,name,age): self.name=name self._age=age @property defage(self): returnself._age defset_age(self,value): ifvalue<=0: raiseValueError('Theagemustbepositive') self._age=valueCodelanguage:Python(python)Toassigntheset_agetothefsetoftheagepropertyobject,youcallthesetter()methodoftheagepropertyobjectlikethefollowing:classPerson: def__init__(self,name,age): self.name=name self._age=age @property defage(self): returnself._age defset_age(self,value): ifvalue<=0: raiseValueError('Theagemustbepositive') self._age=value age=age.setter(set_age)Codelanguage:Python(python)Thesetter()methodacceptsacallableandreturnsanothercallable(apropertyobject).Therefore,[email protected]_age()methodlikethis:classPerson: def__init__(self,name,age): self.name=name self._age=age @property defage(self): returnself._age @age.setter defset_age(self,value): ifvalue<=0: raiseValueError('Theagemustbepositive') self._age=valueCodelanguage:Python(python)Now,youcanchangetheset_age()methodtotheage()methodandusetheagepropertyinthe__init__()method:classPerson: def__init__(self,name,age): self.name=name self.age=age @property defage(self): returnself._age @age.setter defage(self,value): ifvalue<=0: raiseValueError('Theagemustbepositive') self._age=valueCodelanguage:Python(python)Tosummarize,youcanusedecoratorstocreateapropertyusingthefollowingpattern:classMyClass: def__init__(self,attr): self.prop=attr @property defprop(self): returnself.__attr @prop.setter defprop(self,value): self.__attr=valueCodelanguage:Python(python)Inthispattern,the__attristheprivateattributeandpropisthepropertyname.Thefollowingexampleusesthe@propertydecoratorstocreatethenameandagepropertiesinthePersonclass:classPerson: def__init__(self,name,age): self.name=name self.age=age @property defage(self): returnself._age @age.setter defage(self,value): ifvalue<=0: raiseValueError('Theagemustbepositive') self._age=value @property defname(self): returnself._age @name.setter defname(self,value): ifvalue.strip()=='': raiseValueError('Thenamecannotbeempty') self._age=valueCodelanguage:Python(python)SummaryUsethe@propertydecoratortocreateapropertyforaclass.PreviouslyPythonPropertyUpNextPythonReadonlyPropertySearchfor:Classes&ObjectsSpecialMethodsPropertySingleInheritanceEnumerationsSOLIDPrinciplesMultipleInheritanceDescriptorsMetaProgrammingExceptions



請為這篇文章評分?