Summary of differences between Single and Double underscores in Python and python underline

Source: Internet
Author: User

Summary of differences between Single and Double underscores in Python and python underline

Preface

The Python code style is described by PEP 8. This document describes all aspects of the Python programming style. By following this document, the Python code written by different programmers can maintain the most similar style. This makes it easy to read and communicate with programmers.

When we are learning Python, it seems that many people do not understand why there are several underscores in front of the method, sometimes even on both sides, 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.

Let's take a look at the specific analysis below.

Starting with an underscore

We often see a single underline in front of a method or attribute, and think that it indicates the method or attribute is of this type (like Python and Golang, not only classes can have methods, private methods or attributes of many types or even basic types can also be defined. However, in Python, there are no private methods or attributes in the real sense. The preceding underscore _ indicates that you should not access this method or attribute because it is not part of the API.

For example:

Pythonclass BaseForm(StrAndUnicode): ... def _get_errors(self): "Returns an ErrorDict for the data provided for the form" if self._errors is None: self.full_clean() return self._errors errors = property(_get_errors)

This code snippet is from Django source code (django/forms. py ). The design of this Code is that the errors attribute is part of the external API. If you want to obtain the error details, you should access the errors attribute instead of (and should not) access the _ get_errors method.

Begin with Double underline

Many people have told me that Python uses double-underline to start with private, and I have seen such a statement in many places. This understanding may not be wrong, but it is not the original intention and purpose of designing a Double underline at the beginning of Python. The real purpose of designing this in Python is only to prevent subclass from overwriting the parent class.

Let's look at an example:

class A(object):  def __method(self): print("I'm a method in class A") def method_x(self): print("I'm another method in class A\n") def method(self): self.__method() self.method_x()class B(A):  def __method(self): print("I'm a method in class B") def method_x(self): print("I'm another method in class B\n")if __name__ == '__main__':  print("situation 1:") a = A() a.method() b = B() b.method() print("situation 2:") # a.__method() a._A__method() 

Execution result:

situation 1:I'm a method in class AI'm another method in class AI'm a method in class AI'm another method in class Bsituation 2:I'm a method in class A

Note the following two points:

In Class A, we define three methods: _ method (), method_x, and method (). Then we redefine Class B and inherit from Class, override overwrites the _ method () and method_x methods of the parent class in Class B. However, from the output result, object B calls method () the _ method () method of its parent class A and its own method_x () method are called. That is to say, the _ method () overwrite does not take effect, but the method_x () overwrite takes effect. This is exactly the sole purpose of designing a Double underline in Python.

You can also obtain the answer in the official Python explanation: https://www.python.org/dev/peps/pep-0008/?method-names-and-instance-variables.

As we mentioned above, Python does not have private variables in the real sense. Although the methods and attributes starting with double underscores cannot be directly referenced, it is because Python adds the prefix _ class name before it by default, so it is like the code below situation 2, although we cannot use a to directly access _ method (), we can add A prefix to access _ a _ method ().

Double underline at the beginning and end

In general, the method with double-underline at the beginning and end of _ this _ indicates that this is called by Python. You do not need to call this method. For example, we can call the len () function to calculate the length. In fact, it calls the _ len _ () method in the background. Generally, we should use len instead of _ len __():

A = [1, 2, 3] print (len (a) print (. _ len _ () # equivalent to num = 10 print (num + 10) print (num. _ add _ (10) # equivalent to the above

We generally call the _ len _ () method magic methods. Some operators call magic methods in the background. For example, + the backend operator calls _ add __, -The call is _ sub __, so this mechanism allows us to override operators in our own classes (see the following example ). In addition, in some special scenarios, the Double underline at the beginning and end is only a callback function. For example, _ init _ () will be called during object initialization, __new __() it is called when an instance is built. Here are two examples:

class CrazyNumber(object): def __init__(self, n):  self.n = n  def __add__(self, other):  return self.n - other  def __sub__(self, other):  return self.n + other  def __str__(self):  return str(self.n) num = CrazyNumber(10) print(num) # output is: 10print(num + 5) # output is: 5print(num - 20) # output is: 30

In the above example, we overwrite the + and-operators to switch their functions. Let's look at another example:

class Room(object): def __init__(self):  self.people = []  def add(self, person):  self.people.append(person)  def __len__(self):  return len(self.people) room = Room() room.add("Igor") print len(room) # output is: 1

In this example, the Room object can also use the len function because we implement _ len.

All such methods are described here: documentation.

Conclusion

  • Starting with a single underscore (_ one_underline), it indicates that the method is not part of the API and cannot be accessed directly (although there is no syntax problem ).
  • Starting with a double underline (_ two_underlines) indicates that the subclass cannot override this method. Do not use this method unless you really know what you are doing.
  • When you want to make your own defined objects use Python built-in functions or operators (such as len, add, +,-, =) like Python built-in objects, you can define this method.
  • Of course, some attributes are only added but underlined at the end. This is only to avoid conflicts between some of our names and the reserved keywords in Python, with no special meaning.

Note:For most of the content in this article, refer to self-Difference between _, and _ xx in Python.

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

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.