0

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?

NotAName
  • 3,821
  • 2
  • 29
  • 44
  • You have duplicate method definitions for `Bar.a`. The second one replaces the first one. – Barmar May 17 '22 at 01:11
  • @Barmar, I'm not sure I understood correctly. Could you elaborate? – NotAName May 17 '22 at 01:14
  • You define `a()` multiple times (`def a()`). The last definition over-writes the previous ones – Freddy Mcloughlan May 17 '22 at 01:16
  • The purpose of `property.getter` isn't to create "explicit getters". `property.getter` creates a new property as a copy of an existing property, with the getter replaced. It is occasionally useful, if you find yourself actually wanting to do that for some reason, but it mostly just exists for symmetry with `property.setter` and `property.deleter`. – user2357112 May 17 '22 at 01:16

0 Answers0