private class members and hasattr

D

Dragos Chirila

Hi

I have the following class:

class PropTest:

def __init__(self):
self.prop1 = 1
self._prop2 = 2
self.__prop3 = 3

def testprops(self):
print 'has prop1 %s' % hasattr(self, 'prop1')
print 'has _prop2 %s' % hasattr(self, '_prop2')
print 'has __prop3 %s' % hasattr(self, '__prop3')


and the following test lines:

a = PropTest()
a.testprops()

The output of this is:

has prop1 1
has _prop2 1
has __prop3 0

Why hasattr method doesn't return 1(true) for private member '__prop3' ??

I tested it with Python 2.2.1 and 2.1.3 .

Thanks

Dragos
 
F

Francis Avila

Dragos Chirila wrote in message ...
Why hasattr method doesn't return 1(true) for private member '__prop3' ??

Because that's how private members work. See "5.2.1 Identifiers (Names)" in
the Python Language Reference.
.... def __init__(self):
.... self.__prop3 = 3
.... def testprops(self):
.... print hasattr(self, '__prop3')
.... print hasattr(self, '_PropTest__prop3')
....
dir(PropTest()) ['_PropTest__prop3', '__doc__', '__init__', '__module__', 'testprops']
PropTest().testprops()
False
True

You're probably better off not using private members anyway.
 
E

Erik Max Francis

Dragos said:
Why hasattr method doesn't return 1(true) for private member '__prop3'
??

I tested it with Python 2.2.1 and 2.1.3 .

Because a prefix double underscore (without a suffixed double
underscore, anyway) mangles the identifier with the intention of it
being private. That is to say, trying to access a __private name from
another class is a good indication that you're doing something you're
not supposed to be doing.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top