When should you use @property in a model class?
You should use @property
when your class attribute is formed from other attributes in the class, and you want it to get updated when source attributes are changed.
Example without @property
class Coordinates():
def __init__(self, x, y):
self.x = 'x'
self.y = 'y'
self.coordinates = [self.x, self.y]
def revers_coordinates(self):
return [self.y, self.x]
>>> a = Coordinates('x', 'y')
>>> a.coordinates
['x', 'y']
>>> a.revers_coordinates()
['y', 'x']
>>> a.x = 'z'
>>> a.coordinates
['x', 'y'] # <===== no changes in a.x
>>> a.revers_coordinates()
['y', 'z']
As you see revers_coordinates()
reacted, and self.coordinates
did not. And if you want it to react, @property
is an option.
Of course you could just change self.coordinates
on function def coordinates(self)
, but this will break all places in your code when it is called as property without ()
(maybe your code is opensource, and it will break not only for you). In this case @property is what you want.
Example with @property
class CoordinatesP():
def __init__(self, x, y):
self.x = 'x'
self.y = 'y'
@property
def coordinates(self):
return [self.x, self.y]
def revers_coordinates(self):
return [self.y, self.x]
>>> a = CoordinatesP('x', 'y')
>>> a.coordinates
['x', 'y']
>>> a.revers_coordinates()
['y', 'x']
>>> a.x = 'z'
>>> a.coordinates
['z', 'y'] # <===== a.x has changed
>>> a.revers_coordinates()
['y', 'z']