Differences between Single and Double underscores in python

Source: Internet
Author: User

Differences between Single and Double underscores in python

When learning Python, many people do not understand why there are several underscores (_ this _) in front of the method, and sometimes even the two sides are added, such as _ this. Before I saw the above article, I always thought that the underlines in Python serve the same purpose as the Case sensitivity of methods/functions in Golang, or the role of private and public in some other languages, but this is not all the original intention of designing Python. The following is a detailed analysis.

There are four naming methods

1. object # public Method
2. _ object _ # built-in method. do not define it like this.
3. _ object # all private and fully protected
4. _ object # semi-protection

Core style: Avoid using underscores as the start of variable names.

Because underlines have special meanings for the interpreter and are symbols used by built-in identifiers, we recommend that programmers avoid using underscores as the beginning of the variable name. Generally, the variable name_object is regarded as "private" and cannot be used outside the module or class. It cannot be imported using 'from module import. When the variable is private, it is a good habit to use _ object To represent the variable.

A single underline + Class name, for example: _ Class _ object, you can access _ object. Because the variable name__ object _ has special meanings for Python, this naming style should be avoided for common variables.

The member variables starting with "single underline" are called protection variables, meaning that only class objects and subclass objects can access these variables themselves; "Double underline" begins with private members, this means that only the class object can access this data, and even the subclass object cannot access this data. (As shown below)

_ Foo, which starts with an underscore, indicates that the class attributes cannot be directly accessed. It must be accessed through the interface provided by the class, and cannot be imported using "from xxx import; _ foo, which starts with a double underline, indicates the private member of the class. _ foo _, which begins with and ends with a double underline, indicates the special identifier used for special methods in python, for example, _ init _ () indicates the constructor of the class.

class Foo():  def __init__():    ...  def public_method():    print 'This is public method'  def __fullprivate_method():    print 'This is fullprivate_method'  def _halfprivate_method():    print 'This is halfprivate_method'  f = Foo()  f.public_method() # OK  f.__fullprivate_method() # Error occur  f._halfprivate_method() # OK  f._Foo__fullprivate_method() # OK

From the above example, we can see that f. _ halfprivate_method () can be accessed directly, indeed. However, according to the python conventions, it should be regarded as private instead of using them externally (if you have to use them). A good programming habit is not to use it externally. In addition, according to the description of Python docs, The _ object and _ object scopes are limited in this module.

Let's take a look at the output of the following program:

class A(object):  def __init__(self):    self.__private()    self.public()  def __private(self):    print 'A.__private()'  def public(self):    print 'A.public()'class B(A):  def __private(self):    print 'B.__private()'  def public(self):    print 'B.public()'b = B()

Preliminary Exploration

The correct answer is:

A. _ private ()
B. public ()

Let's take A look at the attributes of Class A and Class B respectively:

>>> print '\n'.join(dir(A))_A__private__init__public>>> print '\n'.join(dir(B))_A__private_B__private__init__public

Why does Class A have an attribute named _ A _ private? And _ private disappears! Now let's talk about Python's private variable "Straightening.

Python treats a variable that starts with two or more underscores and does not end with two or more underscores as a private variable. Private variables are converted to long format (public) before code generation ). The conversion mechanism is as follows: insert the class name at the front end of the variable, and add an underline character at the front end. This is the so-called Private name mangling ). For example, the _ private identifier in Class A will be converted to _ A _ private, which is why _ A _ private and _ private disappear in the previous section.

Let's talk about two more things:

First, straightening leads to longer identifiers. When it exceeds 255, Python will cut it off. Pay attention to the naming conflicts caused by this.

Second, Python will not perform straightening when all the class names are marked below. For example:

Class ____ (object): def _ init _ (self): self. _ method () def _ method (self): print '____. _ method () 'print' \ n '. join (dir (____)) _ class ____ delattr ____ dict ____ doc ____ getattribute ____ hash ____ init ____ method # Not straightened _ module ____ new ____ reduce ____ performance_ex ____ repr ____ setattr ____ str ____ weakref __ obj = ____() ____. _ method () obj. _ method () # can be called externally ____. _ method ()

Now let's look at why "A. _ private ()" is output!

After straightening, the code of Class A becomes like this:

Class A (object): def _ init _ (self): self. _ A _ private () # This line has changed self. public () def _ A _ private (self): # This line also changes print 'a. _ private () 'def public (self): print 'a. public ()'

Because the _ init _ method is not overwritten when class B is defined, the call is still. _ init __, that is, self. _ A _ private (), which naturally outputs ". _ private.

The following two sections of code increase persuasiveness and increase understanding:

Class C (A): def _ init _ (self): # rewrite _ init _ and no longer call self. _ A _ private self. _ private () # _ C_private self is bound here. public () def _ private (self): print 'C. _ private () 'def public (self): print 'C. public () 'C = c () Answer: C. _ private () C. public ()
Class A (object): def _ init _ (self): self. _ A _ private () # Call an undefined function, but execute self. public () def _ private (self): print 'a. _ private () 'def public (self): print 'a. public () 'A = a () Answer:. _ private (). public ()

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.