Why can I write and read double-underscore variables outside a class, are they not mangled?

Why can the code below run?

class A:
    def __init__(self):
        self.__w = 10

s = A()
s.__w = 20
print(s.__w)  # 20
s.__haha = 1
print(s.__haha)  # 1

>Solution :

You can in fact not read s.__w outside the class before you assign s.__w = 20.

class A:
    def __init__(self):
        self.__w = 10

s = A()
print(s.__w)
Traceback (most recent call last):
  File "mangle.py", line 6, in <module>
    print(s.__w)
AttributeError: 'A' object has no attribute '__w'

By assigning to s.__w from outside the class, you create a separate variable which is not mangled (it’s separate because the original variable is mangled):

class A:
    def __init__(self):
        self.__w = 10

s = A()
s.__w = 20
print(vars(s))
{'_A__w': 10, '__w': 20}

Name mangling occurs only within a class definition: Reference

Leave a Reply