OOP techniques in Python

Steven Bethard steven.bethard at gmail.com
Thu Apr 27 13:30:35 EDT 2006


Panos Laganakos wrote:
> we usually define private properties and provide public functions
> to access them, in the form of:
> get { ... } set { ... }
> 
> Should we do the same in Python:
> 
> self.__privateAttr = 'some val'
> 
> def getPrivateAttr(self):
>     return self.__privateAttr
> 
> Or there's no point in doing so?

There is no point in doing so.  You should use plain attributes whenever 
possible (that is, whenever you're really just doing a get or a set, 
with no computation).  The only reason to use getters and setters is so 
that you can change the implementation later if you need to.  But python 
allows you to do this with properties:

 >>> class C(object):
...     def __init__(self, x):
...         self.x = x
...
 >>> C(42).x
42
 >>> class C(object):
...     def _get_x(self):
...         return self._x * 2
...     def _set_x(self, value):
...         self._x = value / 2
...     x = property(_get_x, _set_x)
...     def __init__(self, x):
...         self.x = x
...
 >>> C(42).x
42

Which should not be interpreted as saying you should start writing a 
bunch of properties now. ;) Instead, only introduce a property when you 
find that something must remain an attribute (presumably for backwards 
compatibility reasons) but for whatever reason it now needs some 
additional computation.

STeVe



More information about the Python-list mailing list