< BACKMake Note | BookmarkCONTINUE >
156135250194107072078175030179198180025031194137176049106218111004231202153041135146141026

Privacy

Attributes in Python are, by default, "public" all the time, accessible by both code within the module and modules that import the module containing the class.

Many OO languages provide some level of privacy for the data and provide only accessor functions to provide access to the values. This is known as implementation hiding and is a key component to the encapsulation of the object. Most OO languages provide "access specifiers" to restrict who has access to member functions.

Python 1.5 introduces an elementary form of privacy for class elements (attributes or methods). Attributes which begin with a double underscore (__) are mangled during run-time so direct access is thwarted. In actuality, the name is prepended with an underscore followed by the class name. For example, let us take the self.__num attribute found in Example 13.2 (numstr.py). After the mangling process, the identifier used to access that data value is now self._NumStr__num. Adding the class name to the newly-mangled result will prevent it from clashing with the same name in either ancestor or descendant classes.

Although this provides some level of privacy, the algorithm is also in the public domain and can be defeated easily. It is more of a protective mechanism for importing modules that do not have direct access to the source code or for other code within the same module.

One way to prevent the source code from being accessed is to allow only access to the byte-compiled .pyc file. For example, a software company shipping Python software may choose to provide only the .pyc files. This helps to ensure that no one can maliciously gain programmatic access to private variables and methods.

As we discovered in Chapter 12, simple module-level privacy is provided by using a single underscore character prefixing an attribute name. This prevents a module attribute from being imported with "from mymodule import *".


Last updated on 9/14/2001
Core Python Programming, © 2002 Prentice Hall PTR

< BACKMake Note | BookmarkCONTINUE >

© 2002, O'Reilly & Associates, Inc.