Class design (information hiding)

Daniel Larsson daniel.j.larsson at gmail.com
Fri Sep 7 06:03:10 EDT 2007


On 9/7/07, Alexander Eisenhuth <newsuser at stacom-software.de> wrote:
>
> Hi all,
>
> I'm wodering how the information hiding in python is ment. As I understand
> there
>   doesn't exist public / protected / private  mechanism, but a '_' and
> '__'
> naming convention.
>
> 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?)


Strictly speaking, everything is public in python. Members prefixed with
"__" just get name mangled. But conceptually, yes, there is only public and
private members. Information hiding is based on convention, otherwise it
would be hard to write debuggers in python, which by definition wants to
break the information hiding principle. If you're not writing a debugger,
doc generator, or other type of meta level program, follow the conventions
of not peeking under the hood.

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'.


This is so that in class B, you can also have members called __getY and __z,
and they won't interfere with class A (they'll be called _B__getY and _B__z
respectively ).

What would you say to a C++ Programmer about class interfaces in big Python
> systems? What is the idea behind the _ and __ naming.


As a rough analogy:

__name -> private
_name -> protected

Use or don't use '_'
> methods ? (As Designer of the software, as Programmer of the software)


I don't know if you're making a distinction here between "designer" and
"programmer". Are you meaning "implementer of library" and "user of
library"? As a user of a library, never ever explicitly call members
starting with an underscore.

Regards Alexander
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070907/a3a402ed/attachment.html>


More information about the Python-list mailing list