The property
function gives us a handy way to
implement a simple descriptor without defining a separate class. Rather
than create a complete class definition, we can write getter and setter
method functions, and then bind these functions to an attribute
name.
This allows us to create programs that look like the following
example.
>>>
oven= Temperature()
>>>
oven.farenheit= 450
>>>
oven.celsius
232.22222222222223
>>>
oven.celsius= 175
>>>
oven.farenheit
347.0
In this example, we set one attribute and the value of another
attribute changes to mirror it precisely. We can do this by defining
some method functions and binding them to attribute names.
Property Design Pattern. The Property design pattern has a number of method functions
which are bound together with a single property name. The method
functions can include any combination of a getter, a setter and a
deleter.
To create a property, we define the instance variable and the
method functions for some combination of getting, setting and deleting
an attribute value. This is identical with the
Getter and Setter
design pattern. To make a
property, we provide these method functions to the
property
function to bind the various methods to an
attribute name.
Here's the definition of the property
function.
-
property
(
fget
,
fset
,
fdel
,
doc
)
→ property attribute
-
Binds the given method functions into a property definition.
This builds a descriptor object. Usually the result value is
assigned to an attribute of a class.
Property Example. The following example shows a class definition with four method
functions that are used to define two properties.
Example 25.2. property.py
class Temperature( object ):
def fget( self ):
return self.celsius * 9 / 5 + 32
def fset( self, value ):
self.celsius= (float(value)-32) * 5 / 9
farenheit= property( fget, fset )
def cset( self, value ):
self.cTemp= float(value)
def cget( self ):
return self.cTemp
celsius= property( cget, cset, doc="Celsius temperature" )
|
We create the farenheit property from
the fget and
fset method functions. When we use the
farenheit attribute on the left side of an
assignment statement, Python will use the setter method. When we
use this attribute in an expression, Python will use the getter
method. We don't show a deleter method; it would be used when
the attribute is used in a
del
statement.
|
|
We create the celsius property from the
cget and cset
method functions. When we use the celsius
attribute on the left side of an assignment statement, Python
will use the setter method. When we use this attribute in an
expression, Python will use the getter method.
The doc string provided for the celsius
attribute is available as
Temperature.celsius.__doc__ .
|