Private variables in Python

private variables | Python Methods and Functions

There are no "private" instance variables in Python that cannot be accessed except inside an object. However, most Python code and coders follow a convention, i.e. A name prefixed with an underscore. For example, _geek should be considered a non-public part of the API or any Python code, be it a function, method, or data member. Going through this, we would also try to understand the concept of various forms of trailing

# Python code to illustrate how distortion works

class Map :

def __ init __ ( self , iterate):

  self . list = []

  self .__ geek (iterate)

def geek ( self , iterate):

for item in iterate:

self . list . append (item)

  

  # personal copy of the original geek () method

__ geek = geek 

  

class MapSubclass ( Map ):

  

# provides a new signature for geek (), but

# does not break __init __ ()

  def geek ( self , key, value): 

for i in zip (keys, values):

self . list . append (i)

The mangle rules are designed primarily to avoid accidents, but it is still possible to access or change a variable that considered private. It can even be useful in special circumstances such as a debugger.

_Single leading underscores

So one underscore at the beginning of a method, a function or data member means that you shouldn't refer to this method because it is not part of the API. Let's take a look at this piece of code:

# Python code for illustration
# how one works underline

def _ get_errors ( self code> ):

if self ._ errors is None :

self . full_clean ()

return self ._ errors

 

 errors = property (_ get_errors)

Snippet taken from Django source code (django / forms / forms.py). This suggests that errors are a property and also part of the API, but the _get_errors method is "private" so it should not be accessed.

__Double underscores

The two underscores at the beginning cause a lot of confusion. It's more about syntax than convention. double underscores will mangle the attribute names of the class to avoid attribute name conflicts between classes. For example:

# Python code illustrating doubling
# underline at the beginning of work

class Geek:

def _ single_method ( self ):

pass

def __ double_method ( self ): # to distort

pass

class Pyth (Geek):

  def __ double_method ( self ): # to distort

pass

__Double underscores and double trailing underscores__

There is another case of double leading and trailing underscores. We follow this when using special variables or methods (called "magic method") such as __len__, __init__. These methods provide special syntax for names. For example, __file__ specifies the location of the Python file, __eq__ is executed when the expression == b is executed. 
Example:

# Python code to illustrate double leading and
# double underscore closure

class Geek:

 

# & # 39; __ init __ & # 39; for initialization, this is

# special method

def __ init __ ( self , ab): 

self . ab = ab

 

# special custom method. try not to use it

def __ custom__ ( self ): 

pass

This article provided by Chinma Lenka . 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. 
I have referred to the Python docs, hackernoon.com and igorsobreira.com

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.



Private variables in Python: StackOverflow Questions

Answer #1

Private variables in python is more or less a hack: the interpreter intentionally renames the variable.

class A:
    def __init__(self):
        self.__var = 123
    def printVar(self):
        print self.__var

Now, if you try to access __var outside the class definition, it will fail:

>>> x = A()
>>> x.__var # this will return error: "A has no attribute __var"

>>> x.printVar() # this gives back 123

But you can easily get away with this:

>>> x.__dict__ # this will show everything that is contained in object x
               # which in this case is something like {"_A__var" : 123}

>>> x._A__var = 456 # you now know the masked name of private variables
>>> x.printVar() # this gives back 456

You probably know that methods in OOP are invoked like this: x.printVar() => A.printVar(x), if A.printVar() can access some field in x, this field can also be accessed outside A.printVar()...after all, functions are created for reusability, there is no special power given to the statements inside.

The game is different when there is a compiler involved (privacy is a compiler level concept). It know about class definition with access control modifiers so it can error out if the rules are not being followed at compile time

Answer #2

It"s cultural. In Python, you don"t write to other classes" instance or class variables. In Java, nothing prevents you from doing the same if you really want to - after all, you can always edit the source of the class itself to achieve the same effect. Python drops that pretence of security and encourages programmers to be responsible. In practice, this works very nicely.

If you want to emulate private variables for some reason, you can always use the __ prefix from PEP 8. Python mangles the names of variables like __foo so that they"re not easily visible to code outside the class that contains them (although you can get around it if you"re determined enough, just like you can get around Java"s protections if you work at it).

By the same convention, the _ prefix means stay away even if you"re not technically prevented from doing so. You don"t play around with another class"s variables that look like __foo or _bar.

Tutorials