The property decorator in Python
Introduction
This is a continuation of the article
«Classes»
from the section
«OOP in Python»
.
Knowledge from the following articles will help you understand this material better:
Methods
,
Class methods
,
Static methods
,
super()
,
Decorators
,
isinstance()
The partner of this article is my hosting provider beget.com
Background
Let's look at a simple class
class Employee: def __init__(self, first, last): self.first = first self.last = last self.email = first + '.' + last + '@beget.com' def fullname(self): return f'{self.first} {self.last}' emp_1 = Employee("Ivan", "Petrov") print(emp_1.first) print(emp_1.email) print(emp_1.fullname())
python property_deco.py
Ivan Ivan.Petrov@beget.com Ivan Petrov
Let's change only the first attribute of emp_1 and see how the output changes
class Employee: def __init__(self, first, last): self.first = first self.last = last self.email = first + '.' + last + '@beget.com' def fullname(self): return f'{self.first} {self.last}' emp_1 = Employee("Ivan", "Petrov") # Change the attribute emp_1.first = 'Andrei' print(emp_1.first) print(emp_1.email) print(emp_1.fullname())
python property_deco.py
Andrei Ivan.Petrov@beget.com Andrei Petrov
As you can see, email stayed the same, as if the employee were still named Ivan. This attribute was created together with the object and
nobody touched it after that.
fullname was updated because this method reuses the current attributes every time.
What should you do if email needs to be updated automatically?
If you remove the email attribute and create an email method instead, by analogy with fullname, it will work, but everyone who used
this class will have to change their code. This breaks backward compatibility.
Note the method call - you need to add ()
class Employee: def __init__(self, first, last): self.first = first self.last = last # self.email = first + "." + last + "@beget.com" def fullname(self): return f"{self.first} {self.last}" def email(self): return f"{self.first}.{self.last}@beget.com" emp_1 = Employee("Ivan", "Petrov") # Change the attribute emp_1.first = "Andrei" print(emp_1.first) print(emp_1.email()) print(emp_1.fullname())
python property_deco.py
Andrei Andrei.Petrov@beget.com Andrei Petrov
You cannot keep both a method and an attribute with the same name - you get an error TypeError: 'str' object is not callable
Andrei Traceback (most recent call last): File "/home/andrei/python/property_deco.py", line 21, in <module> print(emp_1.email()) TypeError: 'str' object is not callable
Example
If you write a method email() and add the decorator @property backward compatibility will not suffer.
class Employee: def __init__(self, first, last): self.first = first self.last = last def fullname(self): return f"{self.first} {self.last}" @property def email(self): return f"{self.first}.{self.last}@beget.com" emp_1 = Employee("Ivan", "Petrov") # Change the attribute emp_1.first = "Andrei" print(emp_1.first) print(emp_1.email) print(emp_1.fullname())
python property_deco.py
Andrei Andrei.Petrov@beget.com Andrei Petrov
setter
Let's add the decorator @property to both methods and try to set fullname
class Employee: def __init__(self, first, last): self.first = first self.last = last @property def fullname(self): return f"{self.first} {self.last}" @property def email(self): return f"{self.first}.{self.last}@beget.com" emp_1 = Employee("Ivan", "Petrov") # Change the attribute emp_1.fullname = "Andrei Olegovich" print(emp_1.first) print(emp_1.email) print(emp_1.fullname)
python property_deco.py
Traceback (most recent call last): File "/home/andrei/python/property_deco.py", line 21, in <module> emp_1.fullname = "Andrei Olegovich" AttributeError: can't set attribute
The setter decorator helps to get rid of the error
@fullname.setter def fullname(self, name): first, last = name.split(' ') self.first = first self.last = last emp_1 = Employee("Ivan", "Petrov") # Change the attribute emp_1.fullname = "Andrei Olegovich" print(emp_1.first) print(emp_1.email) print(emp_1.fullname)
python property_deco.py
Andrei Andrei.Petrov@beget.com Andrei Petrov
deleter
The best way to delete an attribute is with the decorator deleter
@fullname.deleter def fullname(self): print("Delete Name!") self.first = None self.last = None emp_1.fullname = "Andrei Olegovich" print(emp_1.first) print(emp_1.email) print(emp_1.fullname) del emp_1.fullname print(emp_1.fullname)
python property_deco.py
Andrei Andrei.Olegovich@beget.com Andrei Olegovich Delete Name! None None
Full example code
class Employee: def __init__(self, first, last): self.first = first self.last = last @property def email(self): return f"{self.first}.{self.last}@beget.com" @property def fullname(self): return f"{self.first} {self.last}" @fullname.setter def fullname(self, name): first, last = name.split(' ') self.first = first self.last = last @fullname.deleter def fullname(self): print("Delete Name!") self.first = None self.last = None emp_1 = Employee("Ivan", "Petrov") # Change the attribute emp_1.fullname = "Andrei Olegovich" print(emp_1.first) print(emp_1.email) print(emp_1.fullname) del emp_1.fullname print(emp_1.fullname)
Article author: Andrei Olegovich