liveBook · Manning

Name mangling

As explained in The Quick Python Book, Fourth Edition

Name mangling is Python's transformation of names beginning with two underscores by prepending a class-based prefix to reduce accidental access and inheritance collisions.

Python name mangling transforms names that begin with two underscores and do not end with two underscores. It helps reduce accidental access and keeps similarly named private attributes distinct across classes. section 15.9 section 15.11

The practical rules are:

  • A name such as `__y` in class `Mine` is stored as `_Mine__y`; methods with matching names are mangled too. section 15.9
  • The original spelling `m.__y` does not access the attribute, but a method in `Mine` can use `self.__y`. Mangling is not enforced privacy: the transformed name can be used deliberately. section 15.9

A private instance variable

With `self.__y = 3` in `Mine`, `m.__y` raises `AttributeError`, while `m.print_y()` can print the value. The stored attribute is named `_Mine__y`. section 15.9

dir(m)
 
['_Mine__y',
 ...
 'print_y',
 'x']

Inspect the instance’s attributes to see the mangled name `_Mine__y`. section 15.9

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines the naming rule and demonstrates transformed names and access behavior, while clarifying that mangling is not enforced privacy.
Examples
Demonstrates `Mine.__y`, method access, `dir(m)`, and private members in a superclass and subclass.
What you can do after
Apply it by naming instance variables or methods with leading double underscores to reduce accidental access.
How it connects
Connects private instance variables and methods with class namespaces, inheritance, and attribute access.

Also explained in

Compare how 3 books explain name mangling →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.