Python Property Decorator - TutorialsTeacher

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

The @property decorator is a built-in decorator in Python for the property() function. Use @property decorator on any method in the class to use the method as a ... C# ASP.NETCore MVC IoC TypeScript Angular Python SQLServer MongoDB More ✕ .NETTutorials C# ASP.NETCore ASP.NETMVC IoC webapi LINQ ClientSide JavaScript jQuery Node.js D3.js TypeScript Angular11 AngularJS1 Sass ServerSide https Python SQL SQLServer PostgreSQL MongoDB SkillTests ASP.NETCore ASP.NETMVC LINQ C# webapi IoC TypeScript AngularJS Node.js jQuery JavaScript Articles Tests PythonTutorials Python-GetStarted WhatisPython? WheretousePython? PythonVersionHistory InstallPython Python-Shell/REPL Python-IDLE Python-IDEs Python-Syntax Python-Keywords Python-Variables Python-DataTypes Number String List Tuple Set Dictionary Python-Operators Python-if,elif,else Python-WhileLoop Python-ForLoop Python-Function LambdaFunction Python-VariableScope Python-Module ModuleAttributes Python-Packages Python-PIP Python-__main__ Python-Built-inModules OSModule SysModule MathModule StatisticsModule CollectionsModule RandomModule Python-GeneratorFunction Python-ListComprehension Python-Recursion Python-Built-inErrorTypes Python-ExceptionHandling Python-Assert Python-Class Python-ClassInheritance Python-AccessModifiers Python-Decorators @propertyDecorator @classmethodDecorator @staticmethodDecorator Python-DunderMethods Python-DatabaseCRUD Python-Read,WriteFiles Python-Regex Python-TkinterUI Python-Course&Books PythonAPIMethods PythonBuilt-inMethods PythonStringMethods PythonListMethods PythonSetMethods PythonDictionaryMethods Previous Next PythonPropertyDecorator-@property The@propertydecoratorisabuilt-indecoratorinPythonfortheproperty()function. Use@propertydecoratoronanymethodintheclasstousethemethodasaproperty. Youcanusethefollowingthreedecoratorstodefineaproperty: @property:Declaresthemethodasaproperty. @.setter:Specifiesthesettermethodforapropertythatsetsthevaluetoaproperty. @.deleter:Specifiesthedeletemethodasapropertythatdeletesaproperty. DeclareaProperty Thefollowingdeclaresthemethodasaproperty.Thismethodmustreturnthevalueoftheproperty. Example:@propertydecoratorCopy classStudent: def__init__(self,name): self.__name=name @property defname(self): returnself.__name Above,@propertydecoratorappliedtothename()method. Thename()methodreturnstheprivateinstanceattributevalue__name. So,wecannowusethename()methodasapropertytogetthevalueofthe__nameattribute,asshownbelow. Example:AccessPropertydecoratorCopy >>>s=Student('Steve') >>>s.name 'Steve' PropertySetter Above,wedefinedthename()methodasaproperty.Wecanonlyaccessthevalueofthenamepropertybutcannotmodifyit. Tomodifythepropertyvalue,wemustdefinethesettermethodforthenamepropertyusing@property-name.setterdecorator,asshownbelow. Example:PropertySetterCopy classStudent: def__init__(self,name): self.__name=name @property defname(self): returnself.__name @name.setter#property-name.setterdecorator defname(self,value): self.__name=value Above,wehavetwooverloadsofthename()method.Oneisforthegetterandanotheristhesettermethod. Thesettermethodmusthavethevalueargumentthatcanbeusedtoassigntotheunderlyingprivateattribute. Now,wecanretrieveandmodifythepropertyvalue,asshownbelow. Example:AccessPropertyCopy >>>s=Student('Steve') >>>s.name 'Steve' >>>s.name='Bill' 'Bill' PropertyDeleter Usethe@property-name.deleterdecoratortodefinethemethodthatdeletesaproperty,asshownbelow. Example:PropertyDeleterCopy classStudent: def__init__(self,name): self.__name=name @property defname(self): returnself.__name @name.setter defname(self,value): self.__name=value @name.deleter#property-name.deleterdecorator defname(self,value): print('Deleting..') delself.__name Thedeleterwouldbeinvokedwhenyoudeletethepropertyusingkeyworddel,asshownbelow.Onceyoudeleteaproperty,youcannotaccessitagainusingthesameinstance. Example:DeleteaPropertyCopy >>>s=Student('Steve') >>>dels.name Deleting.. >>>s.name Traceback(mostrecentcalllast): File"",line1,in p.name File"C:\Python37\test.py",line6,inname returnself.__name AttributeError:'Student'objecthasnoattribute'_Student__name' Share Tweet Share Whatsapp LearnPythonusingcodingquestionswithanswers. PythonQuestions&Answers WanttocheckhowmuchyouknowPython? StartPythonSkillTest RelatedArticles ClassAttributesvsInstanceAttributesinPython ComparestringsinPython Convertfiledatatolist ConvertUserInputtoaNumber ConvertStringtoDatetimeinPython HowtocallexternalcommandsinPython? Howtocounttheoccurrencesofalistitem? HowtoflattenlistinPython? HowtomergedictionariesinPython? HowtopassvaluebyreferenceinPython? RemoveduplicateitemsfromlistinPython MorePythonarticles Previous Next PythonQuestions&Answers PythonSkillTest PythonLatestArticles



請為這篇文章評分?