Property Function in Python Classes
In Python, the property
function is a built-in method used within a class to define properties for an object.
Syntax
property(fget=None, fset=None, fdel=None, doc=None)
Each argument corresponds to a class method.
Depending on the operation, the property
function will call the appropriate method.
- fget: The method that’s called when the attribute is accessed.
Exampleprint(object.attribute)
- fset: The method that’s called when a value is assigned to the attribute.
Exampleobject.attribute = value
- fdel: The method that’s called when the attribute is deleted.
Exampledel object.attribute
- doc: A string that serves as the property's documentation.
All the parameters for the property
function are optional.
This means you can use any combination of them, depending on your needs.
Note: If you don’t provide one of the parameters, trying to access the corresponding method will result in an error. For example, if you don’t provide a fget
method, you’ll get an error if you try to access the attribute with a statement like print(object.attribute)
.
You can explicitly name each parameter when using the property
function:
Example
name = property(fget=method1, fset=method2, fdel=method3, doc='documentation')
Or you can rely on the parameter order and omit the names:
Example
name = property(method1, method2, method3, 'documentation')
A Practical Example
Let’s create a class called Prova
.
Inside this class, we’ll define three methods: method1
, method2
, and method3
.
- class Prova:
- def __init__(self, name):
- self._name = name
- def method1(self):
- print('Displaying')
- return self._name
- def method2(self, value):
- print('Setting value to ' + value)
- self._name = value
- def method3(self):
- print('Deleting attribute')
- del self._name
- attribute = property(fget=method1, fset=method2, fdel=method3, doc='documentation')
In the last line of the class, we create an attribute using the property() function.
We link the fget
parameter to method1
, fset
to method2
, and fdel
to method3
within the class.
How does the property
function work?
To explain, let’s create an instance of the Prova
class.
object = Prova('Andrea')
The object now inherits all the properties of the class, including the attribute.
When you access the object’s attribute, the property
function automatically calls method1
through the fget parameter.
>>> print(object.attribute)
>>> Displaying
When you assign a new value to the attribute, the property
function calls method2
through the fset parameter.
>>> object.attribute = 'Gaia'
>>> Setting value to Gaia
When you delete the attribute, the property
function calls method3
through the fdel parameter.
>>> del object.attribute
>>> Deleting attribute
In summary, the property
function calls different methods depending on how you interact with the attribute.
This is how the property
function works within Python classes.
And so on.