Does Python have “private” variables in classes?

后端 未结 12 1864
不思量自难忘°
不思量自难忘° 2020-11-21 23:06

I\'m coming from the Java world and reading Bruce Eckels\' Python 3 Patterns, Recipes and Idioms.

While reading about classes, it goes on to say that in Py

12条回答
  •  遥遥无期
    2020-11-21 23:34

    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

提交回复
热议问题