I am playing around with private and protected variables in Python. I have created this simple class.
class Simple:
def __init__(self,foo):
self.__foo = foo
def print_foo(self):
print(self.__foo)
From what I have read, by using the prefix __
I am marking the variable as private. In fact if I try to access it, it will not work:
>> test = Simple(3)
>> print(test.__foo)
AttributeError: 'Simple' object has no attribute '__foo'
However, it lets me "try" to change the value of the variable form outside the class. The value doesn't really change, but it doesn't raise an error
>> test.__foo = 2
>> test.print_foo()
>> print(test.__foo)
3
2
This behavior seems a bit dangerous to me. Am I doing something wrong? Is there a way to raise an error if I try to change the value of a private variable?