0

So I'm trying to make a basic Class function program, and I got stuck at an early phase on something weird. I have functions opening text files to create the Class objects and all, but the problem is that I can't seem to be able to call any object values. Here's the gist of how my objects are generated:

Class MyClass:
    def __init__(self,val1,val2):
         self.__val1 = val1
         self.__val2 = val2

def main():
    dict = {}
    ...
    dict[key] = MyClass(val1, val2)

And at this point I should be able to call the object values with

    dict[key].__val1
    dict[key].__val2 

but keep getting the error in the title.

Grak
  • 99
  • 1
  • 12
  • variables with `__` starting are name mangled with class name to behave as a private variable. They should not be used outside the class definition. if you still want to use it prepend it with `_className` to access it – cmidi Nov 22 '16 at 18:18
  • To be honest I was using "__" only because of imitating earlier codes, not because I knew what their intent was – Grak Nov 22 '16 at 18:56
  • 1
    this might be helpful. http://stackoverflow.com/questions/1301346/the-meaning-of-a-single-and-a-double-underscore-before-an-object-name-in-python – cmidi Nov 22 '16 at 18:57

1 Answers1

1

Double underscore names are mangled by adding "_ClassName" before their name. Inside class methods, you can reference these names with __var1 notation and Python takes care to actually find them for you.

Outside the class body you'll need to provide the full mangled name in order to access it, that is:

print(d[k]._MyClass__val1)

As an aside, even though this might be an example, don't use names like dict; they mask their built-in counterparts. Use a name like d as I have here.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253