Python single/double underline use

Source: Internet
Author: User

In Python programming, you will often encounter functions (function), methods, and attributes (attribute) with the underscore ' _ ' as the prefix, and here is a summary.

There are four main cases:
1 #  Public 2 __object__ # Special, Python system use, user should not define like it 3 __object # Private (name mangling during runtime) 4 # Obey Python Coding convention, consider it as private
1 and 22 situations are easier to understand, not much to explain, and the most confusing are 3 and 4 situations. Before explaining the 3 and 4 scenarios, first understand Python's description of private, there is no concept of protected in Python, either public or private, but the private in Python is not like C + +, Java, It is not a true private, and by name Mangling (name adaptation, the following example illustrates) The mechanism can access private.
1 classFoo ():2     def __init__():3         ... 4     defPublic_method ():5         Print 'This was public method'6     def __fullprivate_method():7         Print 'This is double underscore leading method'8     def_halfprivate_method ():9         Print 'This is one underscore leading method'Ten  Onef =Foo () AF.public_method ()#OK -F.__fullprivate_method()#Error occur -F._halfprivate_method ()#OK

As explained above, Python does not have a real sense of private, see the following methods to access the __fullprivate_method ()

  

Python single/double underline use

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.