Getter and setter methods 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 data validation or transformation.
Implementing Getters and Setters
Getter and setter methods are defined using regular 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")
Copied!
Other than that, they are nothing special. They are simply methods that follow the convention of being named get_ and set_ (with the property name after) and whose function is to get or set the value of an attribute.
Using Getters and Setters
To use these methods, we simply need 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
Copied!
