Name mangling (also called name Decoration name decoration). In many modern programming languages, this technique is used to solve problems that require unique names, such as naming conflicts/overloads.
In Python, a class variable that starts with a double underscore uses the name mangling technique, which automatically adds the class name prefix.
What's the use? You can prevent accidental modification to a subclass or outside of a class. Although a variable with a single underscore also has a private meaning, more is just a convention that can be accessed directly. The variable that starts with the double underscore is more thorough.
See the code below.
#coding =utf-8class A: def __init__ (self): self.__foo = ' foo ' self._bar = ' bar ' a = A () print a.__dict__print a . _barprint A.__foo #这句会报错
Where print a.__dict__ output {' _a__foo ': ' foo ', ' _bar ': ' Bar '}
As you can see, __foo plus the class name prefix becomes _a__foo.
Below is a summary of the Python underline conventions,
- _XXX: Indicates internal use and cannot be imported by the from M Imoprt *
- Xxx_: Indicates avoidance of conflicts with keywords, such as tkinter.toplevel (Master, class_= ' ClassName ')
- __xxx: A more thorough private. With the name mangling technique, the class name prefix is added automatically. cannot be quilt class and out-of-class access.
- __xxx__: A magic method or user-controlled namespace.
More contract details to http://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles
What are the underscore conventions for name_mangling and Python