The following are the various places where _ is used in Python:
Single underscore
In the translator:
_ returns the value of the last executed expression value in Python Prompt / Interpreter
| |
To ignore values:
On several occasions, we do not want the return values at this time to assign these values to Underscore. Used as a one-time variable.
| |
After the name
Python has its own default keywords that we cannot use as a variable name. To avoid this conflict between the python keyword and the variable, we use an underscore after the name
Example:
| |
Before name
An underscore in front of a variable / function / method name indicates to the programmer that it is for internal use only and can be changed whenever the class wants.
Here, the name prefix through an underscore is considered private. If you specify from Import * all name starts with _ will not import. Python does not define really private, so it can be called directly from other modules, if specified in __all__, we also call it weak Private
| |
Python class_file.py
|
|
Call file from hint
& gt; & gt; & gt; from class_file import *
& gt; & gt; & gt; public_api ()
public api
& gt; & gt; & gt; _private_api ()
Traceback (most recent call last):
File "& lt; stdin & gt;" , line 1 , in & lt; module & gt;
NameError: name '_private_api' is not defined
& gt; & gt; & gt; import class_file
& gt; & gt; & gt ; class_file.public_api ()
public api
& gt; & gt; & gt; class_file._private_api ()
private api
Double underline (__)
__leading_double_underscore
Double underscore causes that the python interpreter rewrites the name to avoid conflict in the subclass. The interpreter changes the name of the variable with a class extension and this function known as Mangling.
testFile.py
| |
Call from translator
| |
In the Python Mangling interpreter, change the variable name with ___. So it is used as a private member several times because another class cannot access this variable directly. The main target for __ — use variable / method only in class. If you want to use it outside of the class, you can make the API publicly available
| |
Call from per
| |
__BEFORE AFTER__
A name starting with __ and ending with the same counts for special methods in Python. Python provides these methods in order to use it as a user-dependent overload operator.
Python provides this convention to distinguish a user-defined function from a module function
| |
Call from translator
| |
This article is courtesy of Nirmi Shah . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.
Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.