Private class and instance methods?

D-Man dsh8290 at
Tue Mar 13 18:42:33 CET 2001

On Sat, Mar 10, 2001 at 04:04:14PM -0500, Mark Pilgrim wrote:
| in article 3AAA73BF.9CDCF3B2 at, Erik Max Francis at
| max at wrote on 3/10/01 1:34 PM:
| > How often do people use methods beginning with __ in order to get some
| > amount of privacy with the automatic name mangling that occurs, to get
| > some kind of weak protection, with, say, accessor methods:
| > 
| > [which would of course allow C.getX and C.setX to do something different
| > in the future]?
| There is a better way to do this in Python, using the __getattr__ and
| __setattr__ special methods.

There is another issue to consider with this.  The name mangling
happens at compile time and can mess things up if you use inheritance.
Say, for example, you create a class with the __getattr__ and
__setattr__ methods to do what you want in a general fashion.  Then
you make a subclass of it to avoid duplicating the __setattr__ and
__getattr__ methods.  It won't work anymore due to the name mangling.  

Check the archives for more details on this.  There was a thread a
while back where Alex Martilli explained how that base class could be
made (for __getattr__ only, he left __setattr__ as an exercise for the
reader), but he used a single underscore rather than the doube
underscore (that causes name mangling).

Actually, on second thought, if you only access the variable through
the methods, it should work, but probably not as expected.  

>>> class Example :
...     def __setattr__( self , name , value ) :
...             self.__dict__[ name ] = value
...     def __getattr__( self , name ) :
...             return self.__dict__[name]
>>> o = Example()
>>> print o.__dict__
{'__x': 2}


More information about the Python-list mailing list