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 accessing attributes seem more natural, and their syntax is cleaner and easier to understand.
Defining Properties
The reserved word property is used to define a property. You can optionally pass a getter, a setter, and a deleter 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, you can get and set values using attribute syntax, which makes 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 call a setter or getter method. I simply get the value with ., and set it with =, just as if it were an attribute.
