Usage of Underscores before and after function name in Python

(Comments)

We often find underscore(s) before and after the function name in python while reading the source code. Do you know why and where it has to be used?

I’ll impart the use of underscore in Python’s function name. There are three possibilities of underscore occurred in function name, one underscore at the beginning(_get_name), two underscores at the beginning(__generate), and two underscores at the either side of function(__len__)

One underscore at the beginning:

    Python doesn’t have real private methods, so one underline in the start of a method or attribute means you shouldn’t access this method because it not the part of API.

classBaseForm(StrAndUnicode):
def _get_errors(self):
"Returns an ErrorDict for the data provided for the form"
if self._errors isNone: self.full_clean()
return self._errors

errors

= property(_get_errors)

_get_errors, is “private”, so you shouldn’t access outside the class.

Two underscores in the beginning:

    It makes a lot of confusion. It should not be used to create a private method. It should be used to avoid your method to be overridden by a subclass.

class A(object):
def __test(self):
print"I'm test method in class A"
def test(self):
self.__test()

class B(A):
def __test(self):
print"I'm test method in class B"
a = A()
print a.test() # Output: I'm test method in class A
b
= B() print b.test() # Output: I'm test method in class A

As we have seen, b.test() didn’t call B.__test() methods, as we could expect. Basically it is the correct behavior for __. So, when you create a method starting with __ it means that you don’t want anyone to override it, it will be accessible only from inside the class where it was defined.

Two underlines in the beginning and in the end:

    When we see a method like __this__, don’t call it. Because it means it’s a method which Python calls, not by you. Let’s take a look:

>>> name ="test string"
>>> name.__len__()
11
>>> len(name)
11>>> number =10
>>> number.__add__(40)
50
>>> number +50
60

There is always an operator or native function which calls these magic methods. Sometimes it’s just a hook Python calls in specific situations. For example __init__() is called when the object is created. __new__() is called to build the instance. For more details PEP-8 guide will help more.

Current rating: 4