OOP techniques in Python
Philippe Martin
pmartin at snakecard.com
Thu Apr 27 15:32:15 EDT 2006
Edward Elliott wrote:
> Panos Laganakos wrote:
>> i.e. 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:
>> Or there's no point in doing so?
>>
>> Some other techniques come to mind, but I think that Python tends to
>> allow the programmer to access stuff he wants even though he shouldn't
>> or in the form of a dict or list, rather than a method to do so.
>
> There's no point. Private access can only be advisory anyway -- there are
> ways around it in every language. Convention serves just as well, people
> know that touching _foo is done at their own risk. It's not creating
> extra hoops to jump through the few times you really do need to touch a
> private var.
>
> Others already mentioned how to transparently change attributes to
> properties.
>
> If you're worried about enforcing restrictions in your code base, get a
> lint checker to flag any expression of the form name._foo where name isn't
> 'self'. Yes you can still access _foo other ways, but you'll never get
> perfect enforcement anyway. Maybe the extra step will make you think
> twice, if that's what you want (and it seems to be).
--
What then is the point of the double underscore (if any) ?:
In [2]:class test:
.2.: _one_underscore=1
.2.: __two_underscores=2
.2.:
In [3]:t = test()
In [4]:t._one_underscore=2
In [5]:t.__two_underscores=3
In [6]:t.__two_underscores
Out[6]:3
In [7]:dir (test)
Out[7]:['__doc__', '__module__', '_one_underscore',
'_test__two_underscores']
In [8]:test._one_underscore
Out[8]:1
In [9]:test.__two_underscores
---------------------------------------------------------------------------
exceptions.AttributeError Traceback (most recent
call last)
/home/philippe/<ipython console>
AttributeError: class test has no attribute '__two_underscores'
-------------------------
"Poignée trop essorée, moulin bien rincé"
Pierre Lafouine
---------------------------
More information about the Python-list
mailing list