Python Forum

Full Version: Can access class private variable?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

Am new to Python3 (previously Java)
Below I make a class, instantiate it, and then do 2 things I don't understand (see comments)

Appreciate some help - Michael


class HWClass:

    def __init__(self): 
        self.__classvar = 3 #private
        self.printHW()

    def printHW(self): 
        print("Hello World")

hw = HWClass()  #Instantiation
hw.__classvar = 4  #This suggests I change a private class variable? It doesn't actually change, but the text suggests it does, which is error-prone
hw.varxxxx = 9 #How can I use a variable on this class object that is not defined in the class?
Actually, hw.__classvar does change. Python does not have private variables. There is name mangling, but that's really not worth messing with. There's also properties, but that's more about setters/getters than private variables.

Also, classes accept new variables in their namespace. That's just how Python works. You can limit this behavior with __slots__, but that is rarely, if ever, done.

Python is more about making it easy to do things than it is about making rules that you can't do things.
You can access it bye hw._HWClass__classvar  not hw.__classvar.
>>> hw = HWClass()
>>> hw._HWClass__classvar
3
>>> hw._HWClass__classvar = 4
>>> hw._HWClass__classvar
4
As mention there is nothing private in Python.
__ would say it should not be used before understanding what's it's used for(name mangling).
A quick demo of name mangling.
class HWClass:
    def __init__(self):
        self.__classvar = 3 # Not private, it's for name mangling

class HW(HWClass):
    def __init__(self):
        super().__init__()
        self.__classvar = 3 
Now if use Class HW,
has class variable classvar been named mangled(not overwritten).
>>> hw = HW()
# Both have been given different name(name mangling)
>>> hw._HWClass__classvar
3
>>> hw._HW__classvar
3

# Change one will not change the other
>>> hw._HWClass__classvar = 100
>>> hw._HWClass__classvar
100
>>> hw._HW__classvar
3
It's take some chaining to learn it the Python way,when coming from Java.