Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use properties or getters and setters?

I know that it is not pythonic to use getters and setters in python. Rather property decorators should be used. But I am wondering about the following scenario -

I have a class initialized with a few instance attributes. Then later on I need to add other instance attributes to the class. If I don't use setters, then I have to write object.attribute = value everywhere outside the class. The class will not have the self.attribute code. Won't this become a problem when I need to track the attributes of the class (because they are strewn all over the code outside the class)?

like image 863
debashish Avatar asked May 10 '17 14:05

debashish


1 Answers

In general, you shouldn't even use properties. Simple attributes work just fine in the vast majority of cases:

class X:
    pass

>>> x = X()
>>> x.a
Traceback (most recent call last):
  # ... etc
AttributeError: 'X' object has no attribute 'a'
>>> x.a = 'foo'
>>> x.a
'foo'

A property should only be used if you need to do some work when accessing an attribute:

import random

class X:

    @property
    def a(self):
        return random.random()

>>> x = X()
>>> x.a
0.8467160913203089

If you also need to be able to assign to a property, defining a setter is straightforward:

class X:

    @property
    def a(self):
        # do something clever
        return self._a

    @a.setter
    def a(self, value):
        # do something even cleverer
        self._a = value

>>> x = X()
>>> x.a
Traceback (most recent call last):
  # ... etc
AttributeError: 'X' object has no attribute '_a'
>>> x.a = 'foo'
>>> x.a
'foo'

Notice that in each case, the way that client code accesses the attribute or property is exactly the same. There's no need to "future-proof" your class against the possibility that at some point you might want to do something more complex than simple attribute access, so no reason to write properties, getters or setters unless you actually need them right now.

For more on the differences between idiomatic Python and some other languages when it comes to properties, getters and setters, see:

  • Why don't you want getters and setters?
  • Python is not Java (especially the "Getters and setters are evil" section)
like image 186
Zero Piraeus Avatar answered Sep 30 '22 15:09

Zero Piraeus