Information Hiding

All attributes of a class are public

  • No notion of private or protected members.

However, there is a name-mangling trick.

  • All names in a class that have leading double-underscores are mangled.
  • Identifiers of the form __name become _Classname__name
     class A:
        def __init__(self):
            self.__X = 3          # self._A__X = 3
     class B(A):
        def __init__(self):
            self.__X = 42         # self._B__X = 42
  • This is useful if you need to have private data that is "invisible" to derived classes.
  • Note: can still access if you know the name mangling trick
     class B(A):
         def foo(self):
               print self._A__X   # print A's private data (shame!)
<<< O'Reilly OSCON 2000, Introduction to Python, Slide 99
July 17, 2000, beazley@cs.uchicago.edu
>>>