'Python Encapsulation in deep

class Computer:

    def __init__(self):
        self.__maxprice = 900
        self.minvalue = 200
   

c = Computer()
#print(c.__maxprice) # this will throw an exception
c.__maxprice = 1000 # hear am assigning the new value to my mangled variable
print(c.__maxprice) # this will return the value 1000

As per the encapsulation __maxprice should not be accessible outside but in the above example i am able to update the value and access it.



Solution 1:[1]

Within a class definition, attributes beginning with two underscores are mangled to _classname__attribute. So when you write self.__maxprice inside the class, it's treated as self._Computer__maxprice.

This mangling doesn't happen outside the class definition. So when you write

c.__maxprice = 1000

it creates a new attribute named __maxprice. This is unrelated to the attribute _Computer__maxprice that's assigned in the __init__() method.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barmar