About classes and OOP in Python

bruno at modulix onurb at xiludom.gro
Wed Apr 12 04:43:56 EDT 2006


Ben C wrote:
> On 2006-04-11, Michele Simionato <michele.simionato at gmail.com> wrote:
> 
>>Roy Smith wrote:
>><snip>
>>
>>>That being said, you can indeed have private data in Python.  Just prefix
>>>your variable names with two underscores (i.e. __foo), and they effectively
>>>become private.  Yes, you can bypass this if you really want to, but then
>>>again, you can bypass private in C++ too.
> 
> 
>>Wrong, _foo is a *private* name (in the sense "don't touch me!"), __foo
>>on the contrary is a *protected* name ("touch me, touch me, don't worry
>>I am protected against inheritance!").
>>This is a common misconception, I made the error myself in the past.
> 
> 
> Please explain! I didn't think _foo meant anything special,

It doesn't mean anything special in the language itself - it's a
convention between programmers. Just like ALL_CAPS names is a convention
for (pseudo) symbolic constants. Python relies a lot on conventions.

> __foo
> expands to _classname__foo for some sort of name-hiding. 

s/hiding/mangling/

> What am I
> missing?

the __name_mangling mechanism is meant to protect some attributes to be
*accidentaly* overridden. It's useful for classes meant to be subclassed
(ie in a framework). It has nothing to do with access restriction - you
still can access such an attribute.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list