Python provides a more elegant and concise way to define getters and setters using the property
function.
This function allows you to define a property that is used like an attribute, but with the ability to control its access and modification.
Properties make access to attributes feel more natural, and their syntax is cleaner and easier to understand.
Property Definition
The reserved word property
is used to define a property. An optional getter, setter, and deleter can be passed to this function.
class Persona:
def __init__(self, nombre, edad):
self._nombre = nombre
self._edad = edad
@property
def nombre(self):
return self._nombre
@nombre.setter
def nombre(self, nombre):
if isinstance(nombre, str):
self._nombre = nombre
else:
raise ValueError("The name must be a string")
@property
def edad(self):
return self._edad
@edad.setter
def edad(self, edad):
if isinstance(edad, int) and edad > 0:
self._edad = edad
else:
raise ValueError("The age must be a positive integer")
Using Properties
With the properties defined, values can be retrieved and set using attribute syntax, making the code cleaner and more readable.
persona = Persona("Luis", 25)
print(persona.nombre) # Output: Luis
persona.nombre = "Carlos"
print(persona.nombre) # Output: Carlos
print(persona.edad) # Output: 25
persona.edad = 30
print(persona.edad) # Output: 30
Notice that I don’t have to invoke a setter or getter method. I simply get the value with .
, and set it with =
, just like it were an attribute.