
58
|
Python Pocket Reference
Pseudo-Private Attributes
By default, all attribute names in modules and classes are vis-
ible everywhere. Special conventions allow some limited
data-hiding, but are mostly designed to prevent name colli-
sions (see also the section “Name conventions,” earlier in
this book).
Module privates
Names in modules with a single underscore (e.g., _X), and
those not listed on the module’s
__all__ list, are not copied
over when a client uses
from module import *. This is not
strict privacy, though, as such names can still be accessed
apart from the
from..* statement.
Class privates
Names anywhere within class statements with two leading
underscores only (e.g.,
__X) are mangled at compile time to
include the enclosing class name as a prefix (e.g.,
_Class__X).
The added class-name prefix localizes such names to the
enclosing class and thus makes them distinct in both the
self
instance object and the class hierarchy.
This helps to avoid clashes that arise in the single instance
object at the bottom of the inheritance chain (all assign-
ments to
self.attr anywhere in a framework change the sin-
gle instance namespace). This is not strict privacy, though, as
such attributes can still be accessed via the mangled name.
New Style Classes
In Version 2.2 and later, inheritance search order can be
slightly different in multiple inheritance diamonds if a super-
class inherits from
object (e.g., class A(object) ...