The most common pattern of @property
usage I see in other people's code and the one I use myself is to omit explicit property getters, for example like so:
class Foo:
def __init__(self, a: int):
self.a = a
@property
def a(self):
return self._a
@a.setter
def a(self, val: int):
self._a = val / 3
f = Foo(12)
print(f.a) # 4.0
But then if we do use an explicit getter things change:
class Bar:
def __init__(self, a: int):
self.a = a
@property
def a(self):
return 2
@a.getter
def a(self):
return self._a
@a.setter
def a(self, val: int):
self._a = val / 3
b = Bar(15)
print(b.a) # 5.0
Now the property a
(the one decorated with @property
) is not doing anything but just takes 3 lines of code.
So is the reason why no one seems to use explicit getters is simply because they just add boilerplate code with no specific purpose? Or are there sometimes reasons to use this second pattern?