__* name mangling documentation

Eric Brunel eric.brunel at pragmadev.com
Fri Mar 22 09:46:13 EST 2002


Michel Pelletier wrote:
> http://www.python.org/doc/current/ref/id-classes.html
> 
> sort of left me hanging on why __ name mangling exists and why it would be
> used.

Simple: private attributes and methods:

class C:
  def __init__(self):
    self.__a = 1
    self.b = 2
o = C()
## Attribute "b" has no "__" => no name mangling
## => public => this works:
o.b = 3
print o.b
## Attribute "__a" has a "__" => name mangling
## => private => this doesn't work:
o.__a = 4
print o.__a

This mimicks the behaviour of an attribute declared "private" in languages 
like C++ or Java. Sorry if you already know about all this, but it actually 
implements the OO concept known as "encapsulation": an object should only 
expose attributes and methods that are meaningful to the "outside world". 
Any attribute or method used internally should not be seen from outside the 
object.

> I'm curious because I'm looking at some code right now that uses it in 
> a somewhat tricky way and I want to know why.

I can't figure out what could be "tricky" about private attributes or 
methods: they can only be accessed from inside the class's instances, and 
that's all there is about them... Can you provide an example of what you 
mean by "tricky"?

HTH
 - eric -




More information about the Python-list mailing list