Difference between _, __ and __xx__ in Python
Many people do not really understand the meaning of the underline when they learn python, and give a detailed explanation below.
One underline in the beginning
Python doesn ' t has real private methods, so one underline in the beginning of a method or attribute means you shouldn ' t a Ccess this method, because it's not part of the API. It ' s very common when using properties:
Python does not have a private domain like C + +, a method or property that begins with an underscore means that you cannot access the method or property by object name or class name, that is, the method or property is private and is not visible externally.
The same applies for properties.
class 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 snippet is taken from Django Source code (django/forms/forms.py). This means was a property, and it's part of the errors the API, but the method this property calls, _get_errors is "private", so you Shouldn ' t access it.
Underlines in the beginning
This one causes a lot of confusion. It should not being used to mark a method as private, the goal are to avoid your method to being overridden by a subclass. Let's see an example:
A double underscore begins with a method to prevent subclasses from overriding the method.
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 as follows:
$ python example.py I‘m a method in A
Output is fine, now look at the same kind of __method.
class B(A): def __method(self): print "I‘m a method in B"b = B()b.method()
Guess what the output is? ...
$ python example.pyI‘m a method in A
As can see, A.method() didn ' t call as B.__method() we could expect. Actually the correct behavior for __ . If you create a method starting with your __ ' re saying that you don't want anybody to override it, it'll be acces Sible just from inside the own class.
How does Python does it? Simple, it just renames the method. Take a look:
a = A()a._A__method() # never use this!! please!
$ python example.pyI‘m a method in A
If you try to access a.__method() it won ' t work either, as I said, is __method just accessible inside the class itself.
Underlines in the beginning and in the end
When you see a method like __this__ , the rule was Simple:don ' t call it. Why? Because it means it ' s a method python calls, not for you. Take a look:
>>> name = " Igor ">>> name. __len__ () 4>>> len span class= "n" >name) 4>>> number = 10>>> number. __add__ (20) 30>>> span class= "n" >number + 2030
There is always a operator or native function that calls these magic methods. The idea here's to give you the ability to override operators in your own classes. Sometimes it ' s just a hook python calls in specific situations. __init__(), for example, was called when the object was created so you can initialize it. __new__() is called to build the instance, and so on ...
Here's an example:
ClassCrazynumber(Object):Def__init__(Self,N):Self.N=NDef__add__(Self,Other):ReturnSelf.N-OtherDef__sub__(Self,Other):return self. n + other def __str__ ( self): return str ( self. N)
num = crazynumber ( 10) print num # 10 print num + 5 # 5 Print num -20 #
Another example:
ClassThe(Object):Def__init__(Self):Self.People=[]DefAdd(Self,Person): self. People. Append (person) def __len__ (selfreturn len ( Span class= "BP" >self. People) room = room () room. Add ( "Igor" ) print len (room) # 1
The documentation covers all these special methods.
Conclusion
Use the for Mark you methods as not part of the _one_underline API. Use if you __two_underlines__ ' re creating objects-like native Python objects or you wan ' t to customize behavior in specific Si Tuations. And don ' t use __just_to_underlines it, unless you really know ' re doing!
Underline in Python