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)?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With