The difference between _, __, and __xx__ in Python

Source: Internet
Author: User

The difference between _, __, and __xx__ in Python
This article is the translation, the copyright belongs to the original author, in this translation to the Chinese share to everybody. English original address: Difference between _, __ and __xx__ in Python
In learning Python, many people are confused about the meaning of the various underscores, and have been explained to others many times before, it is time to record it. There is no real private method in the "_" single underline python. To implement a private method similar to C + +, you can underline the method or property of a class by adding an "_" to it, meaning that the method or property should not be called, and it does not belong to the API. This problem often occurs when using the property:
class BaseForm (strandunicode):         ... def _get_errors (self):         " Returns an errordict for the data provided for the form "        if  is None:            self.full_clean ()        return  self._errors        = Property (_get_ Errors

The code snippet above comes from the Django Source (django/forms/forms.py). The errors here is a property that is part of the API, but _get_errors is private and should not be accessed, but can be accessed through errors to access the error result.

"__" Double underline

This double underline creates more confusion, but it is not used to identify a method or property that is private, and the real purpose is to prevent subclasses from overwriting its contents.

Let's look at an example:

class A (object):      def __method (self):          Print " I ' m a method in a "     def method (self): self         . __method () A = A () A.method ()

The output is this:

$ python example.py I ' m a method in a

很好,出现了预计的结果。

现在我们给A添加一个子类,并重新实现一个__method:

class B (A):      def __method (self):          Print " I ' m a method in B "  = B () b.method ()  

现在,结果是这样的:

$ python example.pyi ' m a method in a  

As we have seen, B.method () cannot call the B.__method method. In fact, it is the normal display of the function "__" two underscores.

Therefore, when we create a method that starts with "__" two underscores, this means that the method cannot be overridden, and it is only allowed to be used inside the class.

What do you do in Python? Very simple, it just renamed the method, as follows:

A = A () A._a__method ()  #  never use this!! please!
$ python example.py I ' m a method in a

如果你试图调用a.__method,它还是无法运行的,就如上面所说,只可以在类的内部调用__method。

"__xx__"前后各双下划线

当你看到"__this__"的时,就知道不要调用它。为什么?因为它的意思是它是用于Python调用的,如下:

" Igor " >>> name. __len__ () 4 >>> len (name) 4 >>> number = ten >>> number. __add__ (>>> number + 20 30)

"__xx__" is often the magic methods of an operator or local function call. In the example above, a function of overriding the operator of a class is provided.

In a special case, it is just a hook called by Python. For example, the __init__ () function is called when an object is created, and __new__ () is used to create an instance.

classCrazynumber (object):def __init__(self, N): SELF.N=Ndef __add__(self, Other):returnSELF.N- Otherdef __sub__(self, Other):returnSELF.N + Otherdef __str__(self):returnSTR (SELF.N) Num= Crazynumber (10) PrintNum#TenPrintNum + 5#5PrintNum-20# -

Another example

class(object):def __init__(self): Self.people= []     defAdd (self, person): self.people.append (person)def __len__(self):returnLen (self.people)=Guest () Room.add ("Igor") PrintLen (Guest)#1
Conclusion

Use _one_underline to indicate that the method or property is private and does not belong to the API;

When creating a python call or some special case, use __two_underline__;

Use __just_to_underlines to avoid sub-class overrides!

The difference between _, __, and __xx__ in Python

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.