0

I am new in python and started learning OOP in python. I have come to know that if I want to make an attribute private in python class, I just need to add a double underscore (__) in-front of the attribute name. It should not be accessible from outside, but if I try to re-assign it, it doesn't complain. It seems like another attribute is creating with same name and it is public, not private!!! It's a bit confusing!!

class Class1:
    def __init__(self, x):
        self.__x = x
    def getX(self):
        return self.__x


ob = Class1(10)
print(ob.getX())

ob.__x = 'This should not work!'
print(ob.__x)

print(ob.getX())

output:

10
This should not work!
10
  • 1
    It doesn't complain because *"we're all consenting adults"*. It doesn't *work* because `__double_underscore` invokes name mangling. See e.g. https://stackoverflow.com/q/7456807/3001761. – jonrsharpe Jan 13 '21 at 17:15
  • 1
    @jonrsharpe so it's just replacing __x with _Class1__x, that's why when I am trying re-assign __x = 'This should not work!' it actually works!! and I really can change the value i.e, _Class1__x = 'something else!', and it will work. This means nothing is private actually!! – Sajal hossain Jan 13 '21 at 17:33
  • Yes, you can assign to the mangled attribute. No, nothing is really private, only by convention. – jonrsharpe Jan 13 '21 at 17:34
  • Thanks, jonrsharpe, and mkrieger1. :) – Sajal hossain Jan 13 '21 at 17:37

0 Answers0