Python 101 : Private variables


There are no real private variable in python, but we can keep some variable from being visible from outside the "private" scope.


In our below example we use a special notation "__" to tell python keep our subclass "b" from changing the variable in the parent class "a".

In the "a" class, python changes "__var" into "_a__var", and in the "b" class, python changes "__var" into "_b__var". 

So at the end, we will have two different variable. 


The above code gives us an error:

"AttributeError: 'b' object has no attribute '_b__var'"

We could fix the error by giving the "b" class it own "private" variable "__var":

Comments

Leave as a comment:

Archive