private variables in python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 13

private variables in python

Can anyone pls explain what are single undescore and double underscore variables and how they can be accessed outside of any class?

26th May 2019, 5:13 PM
Sahil Rana
Sahil Rana - avatar
16 Answers
+ 15
You can access them just by writing them with the underscores: print(yourInstance._thatValue) Python has no privacy. It relies on the convention that programmers *voluntarily* don't touch members that start with _.
26th May 2019, 5:20 PM
HonFu - avatar
+ 8
Single Underscore: > In Interpreter >> After a name >> Before a name ** *** Double Underscore: __leading_double_underscore __before_after__
7th Sep 2021, 7:31 AM
Kedar - avatar
+ 3
if we want to calculate how much money we will have on the 5th day, we can use this expression: 0.01*(2**5) = 0.32 dollars (multiply the penny by 2 raised to the power of 5).
13th Sep 2022, 11:07 AM
nagi madhu
nagi madhu - avatar
+ 2
For everyone saying <variable> = None is declaration without initialization, you are wrong. The assignment operator = is there, meaning something is being assigned to the variable, which defines the variable type and initializes it, even if the thing to be assigned was of a None type.
1st Sep 2021, 8:45 AM
YashVibes - avatar
+ 2
Variable with leading "_" single underscore is just a convention to tell that this variable shall not be imported. You can say it's a soft rule(Rules are meant to be broken XD) Variable with leading '__' double underscore is to tell the interpreter that this variable is not shared and is local to only single class. It's also called name mangling.
7th Nov 2022, 3:52 AM
Adithya Awati
Adithya Awati - avatar
+ 1
To declare private variable as __var And to access this variable as instance name._classname__var
3rd Apr 2021, 1:22 PM
Manish Shee
Manish Shee - avatar
+ 1
If you use a variable with a singel underscore than it is called weakly private, but if you use a variable with doublekunderscore than it is called strongly pirvate
28th Dec 2021, 9:46 PM
Brian Grubb
+ 1
I do not understand the question!
4th May 2022, 10:18 PM
+ 1
Single underscore is private
20th May 2022, 4:25 AM
Fernando Marquez
Fernando Marquez - avatar
+ 1
Privacy doesn't exist in python but you can use conventions like Double underscore for private, if you use a single underscore it means current class
4th Nov 2022, 4:20 AM
Kamran Munawar
Kamran Munawar - avatar
- 1
I can not
14th Jun 2021, 6:47 AM
金阳 su
- 1
25th Oct 2021, 1:39 PM
Ashish Saranshi present
Ashish Saranshi present - avatar
- 1
6th Dec 2021, 11:58 AM
Abd Alghny Sliman
- 1
Yes, is possible.
27th Dec 2021, 3:35 PM
vake soft
vake soft - avatar
- 1
a single underscore at starting is less private and a double underscore at starting is more private
23rd Oct 2022, 4:28 AM
Arsenal Creation
- 1
29th Nov 2022, 7:03 PM
Erik Bothe
Erik Bothe - avatar