Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the private variable is not generating error?

Tags:

python

class Dice:
    def __init__(self):
        self.__value=22
    def showvalue(self):
        return self.__value

d=Dice()
d.__value=6
print(d.showvalue())

I am learning OOPs with Python. In the above program why no error is coming for setting __value outside the class Dice, but the value is not getting set. I am getting 22 as return from showvalue().

like image 465
user2779311 Avatar asked Jul 19 '26 08:07

user2779311


1 Answers

Because python uses name mangling, changing the property names of double underscore elements, for example:

class Dice:
    def __init__(self):
        self.__value=22
    def showvalue(self):
        return self.__value

d=Dice()
print(dir(d))
>>> ['_Dice__value', '__class__', ... , 'showvalue']

You will not find __value, instead it's accesible in the class instance as _Dice__value:

d=Dice()
print(d._Dice__value)

>>> 22

You can modify it:

d=Dice()
d._Dice__value = 6
print(d._Dice__value)
>>> 6
print(d.showvalue())
>>> 6 

So basically you shouldn't use __ or _ outside of the class declaration unless you know exactly what you are doing, and even so that practice is not recommended.

Edit: as stated by @martineau it might be useful to explain what d.__value is doing:

d=Dice()
d.__value=6

print(dir(d))
>>> ['_Dice__value', '__class__', ... , '__value', 'showvalue'] 

print(d.__value)
>>> 6

print(d.showvalue())
>>> 22

In this case, you are adding a new property to the class instance d: __value. python only enforces pseudo-private attribute rules when defining the class. Remember that at this point the d instance has two different properties: __value and _Dice__value. Anything inside the class Dice when it was defined that uses self.__value maps to _Dice__value and since __value was dynamically added later to d it can be accessed outside the class declaration.

like image 99
marcos Avatar answered Jul 20 '26 21:07

marcos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!