预计阅读本页时间:-
Name Mangling Overview
Here’s how name mangling works: names inside a class statement that start with two underscores but don’t end with two underscores are automatically expanded to include the name of the enclosing class. For instance, a name like __X within a class named Spam is changed to _Spam__X automatically: the original name is prefixed with a single underscore and the enclosing class’s name. Because the modified name contains the name of the enclosing class, it’s somewhat unique; it won’t clash with similar names created by other classes in a hierarchy.
Name mangling happens only in class statements, and only for names that begin with two leading underscores. However, it happens for every name preceded with double underscores—both class attributes (like method names) and instance attribute names assigned to self attributes. For example, in a class named Spam, a method named __meth is mangled to _Spam__meth, and an instance attribute reference self.__X is transformed to self._Spam__X. Because more than one class may add attributes to an instance, this mangling helps avoid clashes—but we need to move on to an example to see how.