Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading