Python property() Function
Description
property() The function returns the value of an attribute in new-style classes.
Syntax
The following is the syntax of the property() method:
class property([fget[, fset[, fdel[, doc]]]])
Parameters
- fget -- the function that gets the attribute value
- fset -- the function that sets the attribute value
- fdel -- the function that deletes the attribute value
- doc -- the attribute's documentation string
Return Value
Returns a new-style class attribute.
Example
Define a manageable attribute value x
class
C
(
object
)
:
def
init
(
self
)
:
self
.
_x
=
None
def
getx
(
self
)
:
return
self
.
_x
def
setx
(
self
,
value
)
:
self
.
_x
=
value
def
delx
(
self
)
:
del
self
.
_x
x
=
property
(
getx
,
setx
,
delx
,
"
I'm the 'x' property.
"
)
If both the c Is C Instantiation: c.x triggers the getter, c.x = value triggers the setter, and del c.x triggers the deleter.
If the doc parameter is given, it becomes the docstring of the attribute; otherwise, the property function copies the docstring of the fget function (if any).
Using the property function as a decorator makes it easy to create read-only attributes:
class
Parrot
(
object
)
:
def
init
(
self
)
:
self
.
_voltage
=
100000
@
property
def
voltage
(
self
)
:
"""
Get the current voltage.
"""
return
self
.
_voltage
The code above converts the voltage() method into a getter for a read-only attribute of the same name.
The getter, setter, and deleter methods of property can also be used as decorators:
class
C
(
object
)
:
def
init
(
self
)
:
self
.
_x
=
None
@
property
def
x
(
self
)
:
"""
I'm the 'x' property.
"""
return
self
.
_x
@
x
.
setter
def
x
(
self
,
value
)
:
self
.
_x
=
value
@
x
.
deleter
def
x
(
self
)
:
del
self
.
_x
This code is exactly the same as the first example, but note that the names of these extra functions must match the name under property, such as x here.
Python built-in function