class – Does Python have “private” variables in classes?

class – Does Python have “private” variables in classes?

Its cultural. In Python, you dont 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 theyre not easily visible to code outside the class that contains them (although you can get around it if youre determined enough, just like you can get around Javas protections if you work at it).

By the same convention, the _ prefix means stay away even if youre not technically prevented from doing so. You dont play around with another classs variables that look like __foo or _bar.

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

class – Does Python have “private” variables in classes?

As correctly mentioned by many of the comments above, lets not forget the main goal of Access Modifiers: To help users of code understand what is supposed to change and what is supposed not to. When you see a private field you dont mess around with it. So its mostly syntactic sugar which is easily achieved in Python by the _ and __.

Leave a Reply

Your email address will not be published. Required fields are marked *