Getters and setters are functions that allow you to get and set the value of a class attribute, respectively.
They are used to add additional logic to attribute access, such as validation or data transformation.
Implementation of Getters and Setters
Getters and setters are defined using normal methods within the class.
class Persona:
def __init__(self, nombre, edad):
self._nombre = nombre
self._edad = edad
def get_nombre(self):
return self._nombre
def set_nombre(self, nombre):
if isinstance(nombre, str):
self._nombre = nombre
else:
raise ValueError("The name must be a string")
def get_edad(self):
return self._edad
def set_edad(self, edad):
if isinstance(edad, int) and edad > 0:
self._edad = edad
else:
raise ValueError("The age must be a positive integer")
Otherwise, they are nothing special. They are simply methods that follow the convention of being called get_
and set_
(with the property name afterwards) and whose function is to get or set the value of an attribute.
Using Getters and Setters
To use these methods, you simply have to explicitly call the get_
and set_
methods.
persona = Persona("Luis", 25)
print(persona.get_nombre()) # Output: Luis
persona.set_nombre("Carlos")
print(persona.get_nombre()) # Output: Carlos
print(persona.get_edad()) # Output: 25
persona.set_edad(30)
print(persona.get_edad()) # Output: 30