Class design (information hiding)

Wildemar Wildenburger lasses_weil at klapptsowieso.net
Fri Sep 7 05:56:14 EDT 2007


Alexander Eisenhuth wrote:
> As I figured out there is only public and private possible as speakin in 
> "C++ manner". Are you all happy with it. What does "the zen of python" 
> say to that design? (protected is useless?)
> 
Ask it yourself:
   >>> import this

> 
> class A:
>     def __init__(self):
>         self.__z = 1
>         self._z = 2
>         self.z = 3
>     def _getX(self):
>         return "X"
>     def __getY(self):
>         return "Y"
>     def doAnything(self):
>         print self.__getY()
> 
> 
> class B(A):
>     def __init__(self):
>         A.__init__(self)
>         print dir (self)
>  >>> b = B()
> ['_A__getY', '_A__z', '__doc__', '__init__', '__module__', '_getX', 
> '_z', 'doAnything', 'z']
> 
> I was a bit surprised about '_A__getY' and '_A__z'.
> 
In what way exactly? "__*"-type methods are meant to be private to the 
exact class they were defined in, so thats why you get these names 
prefixed with "_A__". If you're confused why that happens at all, look 
for "name mangling".

> What would you say to a C++ Programmer about class interfaces in big 
> Python systems? What is the idea behind the _ and __ naming. Use or 
> don't use '_' methods ? (As Designer of the software, as Programmer of 
> the software)
> 
Don't worry about information-hiding too much. If anyone is determined, 
they can get at any information they want. You should just rely on 
people not directly using a single-underscore method; thats how python 
does it: trust instead of force.
Use the double underscore technique only when you *need* it, that is, 
you don't want a method to be overridden by a subclass -- for whatever 
reason that might be. Generally you can just forget about this type of 
methods.

/W



More information about the Python-list mailing list