You can easily assign values to attributes of a Python class using Python Property. Getter or setter methods are called automatically when using Python Property.
Python Property: what is it exactly and what is this solution for?¶
The Python Property solution is a technique that developers can use as part of the object oriented programming with Python. Programmers can thus define methods which they can then use as if they were attributes. This allows them tomore intuitive access to attributes of a class. Calling the dedicated setter and getter methods thus becomes superfluous. The Python Property solution allows class attributes to be transformed into properties called ” Managed Attributes “.
A Python Property also makes it possible to implement a form of access control: the use of properties makes it possible to ensure that no other method accesses the data of the attribute to make unwanted modifications to it. .
If you use Python to build a web project, we also advise you to consider the Deploy Now solution. This handy tool lets you build and deploy your code directly through GitHub, giving you a huge efficiency advantage for your workflow.
The Python property() function¶
Developers can use the Python property() function to work with properties. They can take advantage of this integrated function without having to import any additional modules. The Python property() function is implemented in the C programming language, for optimal performance.
The syntax of the Python property() function is as follows:
property(fget=None, fset=None, fdel=None, doc=None)
Python
Python property() function parameters are optional. In the summary table below, you will find the meaning of each parameter:
Setting | Meaning |
---|---|
fget | Function to return the attribute value (getter method) |
fset | Function to set attribute value (setter method) |
fdel | Function indicating how the attribute should be removed |
document | Python string describing the property |
The Python Property Decorator¶
It is not necessary to use the property() function to work with properties. A predefined Python Decorator can often be used; this one allows you to use a method of your class as a property. The programming language supports three different decorators with their well-known notation (“@”) allowing you to define a property:
- “@property”: identifies a method of your class as a Python Property;
- “@property-name.setter”: specifies a setter method, which sets the value of a property;
- “@property-name.deleter”: specifies the method for deleting a property.
If you are interested in more advanced Python tutorials, we also advise you to consult the following articles:
Python Property: example¶
A detailed sample code can help you understand how the Python Property solution works and is useful. In the section of code below, we start by creating a class named “Dog”, with the attribute “_name”. If this example is particularly artificial and has no real use, it is nevertheless perfect to illustrate the operation of the Python Property solution.
class Chien:
def __init__(self):
self._nom = "Bello"
Python
As you can see, the constructor does not receive any parameters specifying the name of our dog. Instead, the dog’s name is specified by default, using the value “Bello”. It is therefore possible to create an object of the class with, for example, the following line of code:
Getter and setter methods¶
You can enhance your class using specific getter and setter methods. This can be a good idea for several reasons, especially because they make the code more easy to maintain and because they allow theintegration of additional features. Since names are strings by default, we also want to make sure that a name as a string is actually passed into our class. To do this, we enter the corresponding functional logic in a dedicated setter method to improve the previous definition of our class:
class Chien:
def __init__(self):
self._nom = "Bello"
def getNom(self):
return self._nom
def setNom(self, nom):
if isinstance(nom, str):
self._nom = nom
else:
return
Python
The setter method with the name “setName” is responsible for checking, in an if…else declaration in Python, whether the parameter transmitted corresponds to a character string. This allows, if necessary, to define the name; otherwise, nothing happens.
We also chose to specify a getter method returning the dog’s name.
An object of our class called “Lassie” can be created by following the example below:
lassie = Chien()
lassie.setNom("Lassie")
print(lassie.getNom())
Python
The result is the following (and corresponds to what we wanted):
Unlike other programming languages, Python does not offer no possibility distinguish between class attributes that can be used directly from the outside, without any getter or setter method (in other programming languages these attributes are often characterized as ” audience “), and class attributes should not be easily changeable from the outside (in other programming languages such attributes are instead characterized as “private”). Conventions therefore dictate that attributes of variable names should not be used without getter and setter methods start with an underscore.
Python property() function¶
To avoid having to resort to an explicit function call to change or find out your dog’s name in Python, you can now use a Python Property. For demonstration purposes, we have also chosen to embed a print statement in each of our getter and setter methods.
class Chien:
def __init__(self):
self._nom = "Bello"
def getNom(self):
print("Appel de la méthode getter")
return self._nom
def setNom(self, nom):
if isinstance(nom, str):
self._nom = nom
print("Appel de la méthode setter")
else:
return
nom = property(getNom, setNom)
Python
As you can see, all we had to do was create a new attribute called “name” (without placing an underscore at the beginning, because the Python Property allowed us to address it from the outside without any problems) and assign the result of our function call to it to call the property() function. It then received the two getter and setter methods you already know as parameters.
By now creating another object of the class named “Snoopy”, the difference is already visible:
snoopy = Chien()
snoopy.nom = "Snoopy"
snoopy.nom
Python
It is now possible to easily access the attributes of this class using the dot notation that you should already be familiar with. Here, the result returned by the program is particularly interesting:
Appel de la méthode setter
Appel de la méthode getter
'Snoopy'
Python
The getter and setter methods have not been explicitly called, but they were still executed when the “Snoopy” object was assigned or retrieved using dot notation. The Python Property allowed us to achieve this result.
Python Property Decorator¶
It is possible to achieve the same result with function decorators, which we have already discussed. If so, the sample code looks like this (both “decorated” methods must have the same name):
class Chien:
def __init__(self):
self._nom = "Bello"
@property
def nom(self):
print("Appel de la méthode setter")
return self._nom
@nom.setter
def nom(self, nom):
if isinstance(nom, str):
self._nom = nom
print("Appel de la méthode getter")
else:
return
Python
It is possible to create a new object for this class and use dot notation to set and extract the “name” attribute:
struppi = Chien()
struppi.nom = "Struppi"
struppi.nom
Python
The result is the same as that obtained using the Python-property() function:
Appel de la méthode setter
Appel de la méthode getter
'Struppi'
Python