Underscore vs Double underscore with variables and methods
Can someone please explain the exact meaning of having leading underscores before an object's name in Python?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sagar PardeshiPosted Nov 21, 2019, 2:05 AM
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.
_single_leading_underscore: weak "internal use" indicator. E.g.
from M import *
does not import objects whose name starts with an underscore.
single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.
Tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).
Sagar LadPosted Aug 19, 2021, 3:01 PM
Dipa MehtaPosted Nov 21, 2019, 2:36 AM
Dinesh GabhanePosted Nov 21, 2019, 1:13 AM