Python @property: How to Use it and Why? - Programiz
文章推薦指數: 80 %
The @property Decorator
CourseIndex
ExploreProgramiz
Python
JavaScript
C
C++
Java
Kotlin
Swift
C#
DSA
StartLearningPython
ExplorePythonExamples
PopularTutorials
GettingStartedWithPython
PythonifStatement
whileLoopinPython
PythonLists
DictionariesinPython
Viewalltutorials
PopularExamples
Addtwonumbers
Checkprimenumber
Findthefactorialofanumber
PrinttheFibonaccisequence
Checkleapyear
Viewallexamples
ReferenceMaterials
Built-inFunctions
ListMethods
DictionaryMethods
StringMethods
Viewall
LearningPaths
Challenges
LearnPythonInteractively
TryforFree
Courses
BecomeaPythonMaster
BecomeaCMaster
ViewallCourses
Python
JavaScript
C
C++
Java
Kotlin
Swift
C#
DSA
StartLearning
Python
PopularTutorials
GettingStartedWithPython
PythonifStatement
whileLoopinPython
PythonLists
DictionariesinPython
Viewalltutorials
ReferenceMaterials
Built-inFunctions
ListMethods
DictionaryMethods
StringMethods
Viewall
Python
JavaScript
C
C++
Java
Kotlin
ExplorePythonExamples
PopularExamples
Addtwonumbers
Checkprimenumber
Findthefactorialofanumber
PrinttheFibonaccisequence
Checkleapyear
Viewallexamples
PythonIntroduction
GettingStarted
KeywordsandIdentifier
Statements&Comments
PythonVariables
PythonDataTypes
PythonTypeConversion
PythonI/OandImport
PythonOperators
PythonNamespace
PythonFlowControl
Pythonif...else
PythonforLoop
PythonwhileLoop
Pythonbreakandcontinue
PythonPass
PythonFunctions
PythonFunction
FunctionArgument
PythonRecursion
AnonymousFunction
Global,LocalandNonlocal
PythonGlobalKeyword
PythonModules
PythonPackage
PythonDatatypes
PythonNumbers
PythonList
PythonTuple
PythonString
PythonSet
PythonDictionary
PythonFiles
PythonFileOperation
PythonDirectory
PythonException
ExceptionHandling
User-definedException
PythonObject&Class
PythonOOP
PythonClass
PythonInheritance
MultipleInheritance
OperatorOverloading
PythonAdvancedTopics
PythonIterator
PythonGenerator
PythonClosure
PythonDecorators
PythonProperty
PythonRegEx
PythonExamples
PythonDateandtime
PythondatetimeModule
Pythondatetime.strftime()
Pythondatetime.strptime()
Currentdate&time
Getcurrenttime
Timestamptodatetime
PythontimeModule
Pythontime.sleep()
RelatedTopics
Pythonproperty()
PythonObjectOrientedProgramming
Pythonsetattr()
Pythonvars()
PythonProgrammingBuilt-inFunctions
PythonObjectsandClasses
Python@propertydecorator
Inthistutorial,youwilllearnaboutPython@propertydecorator;apythonicwaytousegettersandsettersinobject-orientedprogramming.
Pythonprogrammingprovidesuswithabuilt-in@propertydecoratorwhichmakesusageofgetterandsettersmucheasierinObject-OrientedProgramming.
Beforegoingintodetailsonwhat@propertydecoratoris,letusfirstbuildanintuitiononwhyitwouldbeneededinthefirstplace.
ClassWithoutGettersandSetters
LetusassumethatwedecidetomakeaclassthatstoresthetemperatureindegreesCelsius.ItwouldalsoimplementamethodtoconvertthetemperatureintodegreesFahrenheit.Onewayofdoingthisisasfollows:
classCelsius:
def__init__(self,temperature=0):
self.temperature=temperature
defto_fahrenheit(self):
return(self.temperature*1.8)+32
Wecanmakeobjectsoutofthisclassandmanipulatethetemperatureattributeaswewish:
#BasicmethodofsettingandgettingattributesinPython
classCelsius:
def__init__(self,temperature=0):
self.temperature=temperature
defto_fahrenheit(self):
return(self.temperature*1.8)+32
#Createanewobject
human=Celsius()
#Setthetemperature
human.temperature=37
#Getthetemperatureattribute
print(human.temperature)
#Gettheto_fahrenheitmethod
print(human.to_fahrenheit())
Output
37
98.60000000000001
TheextradecimalplaceswhenconvertingintoFahrenheitisduetothefloatingpointarithmeticerror.Tolearnmore,visitPythonFloatingPointArithmeticError.
Wheneverweassignorretrieveanyobjectattributeliketemperatureasshownabove,Pythonsearchesitintheobject'sbuilt-in__dict__dictionaryattribute.
>>>human.__dict__
{'temperature':37}
Therefore,man.temperatureinternallybecomesman.__dict__['temperature'].
UsingGettersandSetters
SupposewewanttoextendtheusabilityoftheCelsiusclassdefinedabove.Weknowthatthetemperatureofanyobjectcannotreachbelow-273.15degreesCelsius(AbsoluteZeroinThermodynamics)
Let'supdateourcodetoimplementthisvalueconstraint.
Anobvioussolutiontotheaboverestrictionwillbetohidetheattributetemperature(makeitprivate)anddefinenewgetterandsettermethodstomanipulateit.Thiscanbedoneasfollows:
#MakingGettersandSettermethods
classCelsius:
def__init__(self,temperature=0):
self.set_temperature(temperature)
defto_fahrenheit(self):
return(self.get_temperature()*1.8)+32
#gettermethod
defget_temperature(self):
returnself._temperature
#settermethod
defset_temperature(self,value):
ifvalue",line30,in
延伸文章資訊
- 1[Python教學]@property是什麼? 使用場景和用法介紹
Python內建的@property 用法,本篇描述了property 的兩種特性,和一個實際應用上的場景.
- 2Python Property Decorator - TutorialsTeacher
The @property decorator is a built-in decorator in Python for the property() function. Use @prope...
- 3How does the @property decorator work in Python? - Stack ...
A Python decorator is a function that helps to add some additional functionalities to an already ...
- 4Understand the Property Decorator of Python Classes - Medium
The property decorator is a powerful tool and widely used in Python classes. It allows us to writ...
- 5Python Property Decorator
Introduction to the Python property decorator ... The property accepts a getter and returns a pro...