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 h
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: