OOP techniques in Python

Steven Bethard steven.bethard at gmail.com
Thu Apr 27 14:27:54 EDT 2006


[Please don't top-post]

Steven Bethard wrote:
 > 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:
[snip]
 > 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.

Philippe Martin top-posted:
> Why is that ? to me it makes sense when I see self.__m_var that I'm dealing
> with a member variable taht derived classes will not see/access.

If the OP uses a private attribute in combination with a getter and a 
setter, he's basically still exposing the attribute as public, but 
making it harder to get and set.  There's no reason to do that.  If 
you're going to expose a public API to part of the class that just 
assigns and returns a value (with no computation), you might as well 
make that API an attribute instead of a pair of methods.

STeVe




More information about the Python-list mailing list