What are the underscore conventions for name_mangling and Python

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.