Single underline in Python, double underline, the difference between two heads underline. __python

Source: Internet
Author: User

Sample

>>> 
    class Student (object):
    __name = 0
    _sex = ' Male '


>>> student.__dict__
Mappingproxy ({' __module__ ': ' __main__ ', ' _student__name ': 0, ' _sex ': ' Male ', ' __dict__ ': <attribute ' __dict__ ' Student ' objects>, ' __weakref__ ': <attribute ' __weakref__ ' of ' student ' objects>, ' __doc__ ': None})

> >> student.__name
Traceback (most recent call last):
  File "<pyshell#58>", line 1, in <module>< C9/>student.__name
attributeerror:type object ' student ' has no attribute ' __name '

>>> student._ Student__name

>>> student._sex
' Male '

look carefully and carefully you will find the problem

 summary: we declared a student class that defined a member with an underscore and a double underline, and then we tried to access the members, and we found that the members of the double underscore could not be accessed directly through the __dict__ we see inside the class, Python automatically interprets __name as _student__name, so we use _student__name to access this success. However, _name is unaffected. So: Two underline: Python class built-in members dedicated to distinguish user-defined members of the single underline: Class of ordinary Members of the underline: the parser automatically converted to: _ Class name __ member name, in lieu of the original member, Access needs to be in the original member name before adding _ class name. 
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.