-3

I have a class with private attribute

class DoGood():
     __prv = "i m private"
     def __init__(self):
         self.default_string = self.__prv

     def say_it_aloud(self):
         print self.default_string

I m trying to access the private attribute from python-cli

>>> from sample import DoGood
>>> obj = DoGood()
>>> obj.__prv
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: DoGood instance has no attribute '__pro'

Since its private i m not able to access it But when i try to assign a value i m able to do it

>>> obj.__prv = "changed in subclass"
>>> obj.say_it_aloud()
i m private

However the value inside the class object has not changed. But why i m able to assign it do it serve any purpose

naga4ce
  • 1,527
  • 3
  • 17
  • 21

1 Answers1

2

You are assigning a new attribute to the instance you have created for that class. It is not changing the __prv attribute's value.

print DoGood._DoGood__prv # access a private attribute.

will still output "i am private"

lima
  • 341
  • 2
  • 11
  • not because it is private though, it's because it is a class attribute. – perreal Feb 05 '14 at 07:27
  • Yes @perreal. Even though it was an instance variable, the private attribute will be mapped as _ClassName__attrname, so if we reassign the attribute, it wont change the actual attribute. – lima Feb 05 '14 at 09:04