Odds and Ends

Private Attributes (New in 1.5)

In the last chapter, we noted that every name assigned at the top level of a file is exported by a module. By default, the same holds for classes; data hiding is a convention, and clients may fetch or change any class or instance attribute they like. In fact, attributes are all public and virtual in C++ terms; they’re all accessible everywhere and all looked up dynamically at runtime.

At least until Python 1.5. In 1.5, Guido introduced the notion of name mangling to localize some names in classes. Private names are an advanced feature, entirely optional, and probably won’t be very useful until you start writing large class hierarchies. But here’s an overview for the curious.

In Python 1.5, names inside a class statement that start with two underscores (and don’t end with two underscores) are automatically changed to include the name of the enclosing class. For instance, a name like __X in a class Class is changed to _Class __ X automatically. Because the modified name includes the name of the enclosing class, it’s somewhat unusual; it won’t clash with similar names in other classes in a hierarchy.

Python mangles names wherever they appear in the class. For example, an instance attribute called self. __X is transformed to self._Class _ _ X, thereby mangling an attribute name for instance objects too. Since more than one class may add attributes to an instance, name mangling helps avoid clashes automatically.

Name mangling happens only in ...

Get Learning Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.