instance vs class attributes

Brian van den Broek bvande at po-box.mcgill.ca
Wed Mar 30 06:25:28 CEST 2005


James Stroud said unto the world upon 2005-03-29 20:37:
> Sarir said:
> 
>>Here are my questions:

<SNIP>

>>3) Should private data be written as self._x instead of self.x?
> 
> 
> This is a long standing debate. The usual answer is "we are all grownups 
> here", meaning that self.x is preferred. However, I personally like self._x 
> to let potential users of my code know that I intended it to be private.

<SNIP>

> James

My understanding is that there is no such thing as true privacy with 
Python, since you can always access self._name and self.__mangled_name 
if you want to. (Though the later way of naming makes it a bit 
difficult so as to strongly indicate it is discouraged Example below.) 
Instead of private names, think of them as shy :-)

But I don't think it is correct to say the self.x form is preferred. 
Some support tools, notably pydoc, understand convention that single 
and double leading underscores means the name is shy and respect it:

 >>> class Shy:
     '''My silly example'''
     def _shy_method(self):
         '''I'm a shy docstring'''
         pass
     def public_method(self):
         '''I'm a public docstring'''
         pass
     def __mangled_method(self):
         '''I'm quite shy and a bit of a challenge to call'''
         print "I've been mangled!"

 >>> help(Shy)
Help on class Shy in module __main__:

class Shy
  |  My silly example
  |
  |  Methods defined here:
  |
  |  public_method(self)
  |      I'm a public docstring


You can still use pydoc on the shy methods, though:

 >>> help(Shy._shy_method)
Help on method _shy_method in module __main__:

_shy_method(self) unbound __main__.Shy method
     I'm a shy docstring

 >>> # calling a mangled method name from outside the class
 >>> shy = Shy()
 >>> shy.__mangled_method()

Traceback (most recent call last):
   File "<pyshell#25>", line 1, in -toplevel-
     shy.__mangled_method()
AttributeError: Shy instance has no attribute '__mangled_method'
 >>> shy._Shy__mangled_method()
Ive been mangled!
 >>>

Best,

Brian vdB




More information about the Python-list mailing list