newbie-name mangling?

Brian van den Broek broek at cc.umanitoba.ca
Tue Dec 13 16:38:13 EST 2005


bobueland at yahoo.com said unto the world upon 2005-12-13 15:05:
> I'm reading van Rossum's tutorial. Mostly it is well written and
> examples are given. However sometimes I get lost in a text, when it
> doesn't give any examples and no clues. There are several examples of
> this in chapter 9 about classes. Here's one from 9.6 (Private
> Variables). I quote
> 
> "There is limited support for class-private identifiers. Any identifier
> of the form __spam (at least two leading underscores, at most one
> trailing underscore) is textually replaced with _classname__spam, where
> classname is the current class name with leading underscore(s)
> stripped.
> This mangling is done without regard to the syntactic position of the
> identifier, so it can be used to define class-private instance and
> class variables, methods, variables stored in globals, and even
> variables stored in instances. private to this class on instances of
> other classes. ...
> Outside classes, or when the class name consists of only underscores,
> no mangling occurs. Name mangling is intended to give classes an easy
> way to define "private" instance variables and methods, without
> having to worry about instance variables defined by derived classes, or
> mucking with instance variables by code outside the class. Note that
> the mangling rules are designed mostly to avoid accidents;"
> 
> Could someone provide an example of the above or direct me to a page
> where it is used.
> 
> Bob
> 

Hi Bob,

as a post of mine on the weekend shows, I don't have full mastery of 
the issues here, either. But, on the theory that sometimes the best 
explanations can come from those only a bit further on, here's an 
example. (Do watch for more expert postings and take their word over 
mine :-)
 >>> class Mangled(object):
	def __init__(self, a, b, c):
		self.a = a
		self._b = b
		self.__c = c

	
 >>> m = Mangled('public', 'timid', 'very shy')
 >>> m.a
'public'
 >>> m.b

Traceback (most recent call last):
   File "<pyshell#94>", line 1, in -toplevel-
     m.b
AttributeError: 'Mangled' object has no attribute 'b'
 >>> m._b
'timid'
 >>> m.c

Traceback (most recent call last):
   File "<pyshell#96>", line 1, in -toplevel-
     m.c
AttributeError: 'Mangled' object has no attribute 'c'
 >>> m.__c

Traceback (most recent call last):
   File "<pyshell#97>", line 1, in -toplevel-
     m.__c
AttributeError: 'Mangled' object has no attribute '__c'
 >>> m._Mangled__c
'very shy'
 >>>


The __ mangling is, as I understand it, a way of saying "I don't think 
  you, as a user of the code, should mess with this attribute unless 
you really know what you are doing. Proceed with caution."

It isn't really private as Python lets you get to pretty much 
anything. It is a strong signal, though.

HTH,

Brian vdB





More information about the Python-list mailing list