Search This Blog

Thursday, August 18, 2011

Private class data members

Hi


OK, so I am reading on OOP in Python, and I am an old C/C++ programmer so I have somewhat high expectations ':)' .


My question is regarding private/public variables. Per default, all class data members are public, but if we precede them with a double underscore, they become private.


1) In the following, why can’t I access *data*? It is private, so it should be available to only class methods, which *output* is:





class Test():
__data = 1

def output(self):
print Test.data

ins = Test()
ins.output()




2) The following is OK, i.e. I can’t access the *data* member from outside the class:





class Test():
__data = 1

def output(self):
print Test.data

ins = Test()
print ins.data




3) In the following, why can I access the private member *data* from the outside?





class Test():
__data = 1

def output(self):
print Test.data

Test.data = 2




Any help is appreciated.


Best,

Niles.

http://bit.ly/p64MZq

No comments:

Post a Comment