private variables in python | Sololearn: Learn to code for FREE!

+11

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?

5/26/2019 5:13:57 PM

Sahil Rana

12 Answers

New Answer

+28

Sahil Rana If you declare a variable with single underscore "_" then it is called weakly private and you can access them as HonFu mentioned. If you declare your variable with double underscore "__" then it ie called strongly private and to access it outside the class you need to qualify it with _Classname as say variable is __val in class Test then to access it, you do like this through obj as test = Test() print(test._Test__val) read more here https://www.sololearn.com/learn/Python/2471/

+11

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 _.

+6

Single Underscore: > In Interpreter >> After a name >> Before a name ** *** Double Underscore: __leading_double_underscore __before_after__

+1

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.

+1

I do not understand the question!

+1

Single underscore is private

0

To declare private variable as __var And to access this variable as instance name._classname__var

0

I can not

0

0

0

Yes, is possible.

0

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