Python Tips 8 - Python Properties

in STEMGeeks4 years ago

Python Tips - A little intro to Python Properties

@property decorator

Hi there ! Welcome in a new episode of Python Tips !
Today we are taking a look at the property decorator.


Classic getter an setter

If you are a Java developper and you just switched to Python, perhaps you are doing this:

class Employee(object):
    def __init__(self, name, salary):
        self._name = name
        self._salary = salary
    # Java-style getter/setter
    def getName(self):
        return self._name
    def setName(self, name):
        self._name = name
    def getSalary(self):
        return self._salary
    def setSalary(self, salary):
        self._salary = salary

If you do, you can go burn in hell !

But why ? It's working.

Because, define methods like this is not very Pythonic... Python provide a lot to not have to deal directly with setters an getters.

You can do this instead.

class Employee(object):
    def __init__(self, name, salary):
        self.__name = str()
        self.__salary = float()
        self.name = name
        self.salary = salary
    # Python-style getter/setter
    @property
    def name(self):
        return self._name

    @salary.setter
    def salary(self, new_name):
        if not type(new_name) in [str] or len(new_name) < 2:
            raise TypeError
        else:
            self.__name = float(new_name)

    @property
    def salary(self):
        return self._salary
    
    @salary.setter
    def salary(self, new_salary):
        if new_salary < 0 or not type(new_salary) in [float,int]:
            raise TypeError
        else:
            self.__salary = float(new_salary)

***Much better ! ***

Now you can do this !

>>>e = Employee('li', 1200.12)
>>>e.salary = -1
Traceback (most recent call last):
  File "/home/slash/Documents/Programmation/projets/hive-base/content/series/PythonTips/PythonTips_n8-Properties/static/Employee.py", line 33, in <module>
    e.salary = -1
  File "/home/slash/Documents/Programmation/projets/hive-base/content/series/PythonTips/PythonTips_n8-Properties/static/Employee.py", line 26, in salary
    raise TypeError
TypeError

>>> e.salary # haven't changed
1200.12

Awesome !

Now we know how to use properties in place of get and set methods !

More info on properties here

You made it to the end, bravo! If you have any questions, don't forget to ask. See you next time! If you spot a grammar or vocabulary mistake, please let me know in the comments.

You will be able to find a good part of the articles in this account in this repository.

To go directly to the section you are currently viewing click here.

Latest article in the series Python Tips: Python Tips 7 -A (very) Little Intro to Path Management With Pathlib