Language: EN

uso-getters-setters-propiedades-python

How to Use Getters and Setters Methods, and Properties in Classes in Python

Getters and setters are functions that allow obtaining and setting the value of an attribute of a class, respectively.

They are used to add additional logic to the access of attributes, such as validation or data transformation.

Implementation of Getters and Setters

Getters and setters 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")

Otherwise, they have nothing special. They are simply methods that have the convention of being named get_ and set_ (with the property name behind) and whose function is to obtain or set the value of an attribute.

Use of Getters and Setters

To use these methods, we 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