I encountered a strange issue while using python. consider the below code:
class Foo:
__bar=None
foo=Foo()
foo.bar=10
print(foo.bar)
I beleive I should get an error here. But I get the output as 10. I get the same output even if I change the code as:
foo=Foo()
foo.__bar=10
print(foo.__bar)
can someone explain why I am not getting an error here? Also what should I do to get an error? Edited for additional clarification:
class Foo:
def __init__(self):
self.__bar=10
def get_bar(self):
return self.__bar
foo=Foo()
foo.__bar=20
print(foo.__bar)
print(foo.get_bar())
Can someone explain why I am getting the answer as 20 and 10? I thought I will get an error for trying to access a private instance variable outside the class. Thanks for the help.