Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
3 views
in Python by (3.5k points)
edited by
What is the meaning of using leading underscores before the name of an object in Python? And what's the difference between a double leading underscore and a single leading underscore?

I also want to know that does meaning stays same whether the object in the question is a function, variable, method, etc.?

2 Answers

0 votes
by (10.9k points)
edited by

Single underscore

It is used before an object’s name to indicate other programmers that the method is meant to be private. It is also used in the name of methods which are fully intended to be overridden by subclasses. Ex- _abc

Double underscore

They are used for fully private methods. Ex- if your class is intended to be subclassed and you have attributes which you do not want the subclass to use, you can name them using a double underscore.

The rules of underscores in Python remain the same whether it is an object or a function, etc. Let us see an example of class for better understanding of the difference between the single and double underscores.

 Example-

>>> class ThisClass():

    def __init__(self):

         self.__superprivate = "Orange"

          self._semiprivate = ", Apple"

>>> my_class = ThisClass()

>>> print my_class.__superprivate

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

AttributeError: thisClass instance has no attribute '__superprivate'

>>> print my_class._semiprivate

, Apple

>>> print my_class.__dict__

{'_ThisClass__superprivate': 'Orange', '_semiprivate': ', Apple'}

0 votes
by (106k points)

Sometimes you have what appears to be a tuple with a leading underscore as in

def foo(bar):

    return _('my_' + bar)

In this case, what's going on is that _() is an alias for a localization function that operates on text to put it into the proper language, etc. based on the locale. For example, Sphinx does this, and you'll find among the imports

from sphinx.locale import l_, _

and in sphinx.locale, _() is assigned as an alias of some localization function.

You can use the following video tutorials to clear all your doubts:-

Browse Categories

...