Linux/Unix > Python Essential Reference, Second Edition > 7. Classes and Object-Oriented Programming > Information Hiding | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105087128015175094165224

### Information Hiding

By default, all attributes are “public.” This means that all attributes of a class instance are accessible without any restrictions. It also implies that everything defined in a base class is inherited and accessible within a derived class. This behavior is often undesirable in object-oriented applications because it exposes the internal implementation of an object and it can lead to namespace conflicts between objects defined in a derived class and those defined in a base class.

To fix this problem, all names in a class that start with a double underscore, such as `_ _Foo`, are mangled to form a new name of the form `_``Classname` `_ _Foo`. This effectively provides a way for a class to have private attributes, since private names used in a derived class won’t collide with the same private names used in a base class. For example:

    class A:
       def _ _init_ _(self):
          self._ _X = 3        # Mangled to self._A_ _X

    class B(A):
       def _ _init_ _(self):
          A._ _init_ _(self)
          self._ _X = 37       # Mangled to self._B_ _X

Although this scheme provides the illusion of data hiding, there’s no strict mechanism in place to prevent access to the “private” attributes of a class. In particular, if the name of the class and corresponding private attribute are known, they can be accessed using the mangled name.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.