Sławomir Kwiatkowski

by: Sławomir Kwiatkowski

2024/07/02

Property decorator

The concept of object-oriented programming is related to the concept of encapsulation, i.e. hiding class fields and making only public methods (public API) available to read or change the values of these fields.

Python does not support access modifiers. Using private variables like: _variable is just a matter of convention.
However, you can check the validity of the data using the property decorator.

Based on the Employee class code, let's assume that we want to verify the entered telephone number. We would like to check whether it has the appropriate number of digits and does not contain characters that are not digits.
Thanks to the @property decorator, we can still refer directly to the variable.
Data checking will be done both when creating the object and when assigning a new phone number to the phone attribute.

     
class Employee:

    def __init__(self, name, salary, phone):
        self.name = name
        self.salary = salary
        self.phone = phone

    @property
    def phone(self):
        return self._phone

    @phone.setter
    def phone(self, phone):
        if not phone.isnumeric() or len(phone) != 5:
            raise ValueError('Wrong phone number!')
        self._phone = phone



john_doe = Employee(name="John", salary="Doe", phone="12345") #data check when creating an object
print(john_doe.phone)       
john_doe.phone = "1234a"  #data check when modifying phone attribute. Raises ValueError
print(john_doe.phone)