More random python observations from a perl programmer

Barry A. Warsaw bwarsaw at
Thu Aug 19 19:57:59 CEST 1999

>>>>> "TW" == Thomas Wouters <thomas at> writes:

    TW> There is some namemangling though, for datamembers/functions
    TW> that start with a single _, for hiding/overriding
    TW> purposes. (those mmebers get the classname encoded in, so it's
    TW> dependant on the class it was called on.)

The name manging rule in Python is actually "starts with double
underscore with no trailing underscores".  E.g. __mangled()

I like to call these `private' attributes, but they really aren't in
the C++/Java sense of privateness.  Because their names get mangled in 
a predicatable way, it's quite easy to get at them directly:

>>> class Shy:
... 	def __handsoff(self): print "please don't touch"
>>> me = Shy()
>>> me.__handsoff()
Traceback (innermost last):
  File "<stdin>", line 1, in ?
AttributeError: __handsoff
>>> me._Shy__handsoff()
please don't touch

If you want true privateness, you'll probably want to look at the
Bastion module, ExtensionClass, or some such.

Name mangling still serves an important purpose though.  It allows a
class to be designed for inheritance, with only the public and
`protected' interfaces needing documentation.  If I inherit from class
Shy above, my DerivedShy doesn't need to know that it's base class has
a private method called __handsoff() because my similarly named method
can't collide with it.

>>> class DerivedShy(Shy):
... 	def __handsoff(self): print "touch all you want"
>>> you = DerivedShy()
>>> you.__handsoff()
Traceback (innermost last):
  File "<stdin>", line 1, in ?
AttributeError: __handsoff
>>> you._DerivedShy__handsoff()
touch all you want
>>> you._Shy__handsoff()
please don't touch

My personal coding convention has long been to use "starts with a
single underscore with no trailing underscores" to mean a `protected'
attribute; i.e. one that is intended to be used or overridden by
derived classes.  But there is no language support for this.


More information about the Python-list mailing list