I can’t understand why this code:
class A(object):
def __init__(self):
self.__value = 1
def get_value(self):
return self.__value
class B(A):
def __init__(self):
A.__init__( self )
self.__value = 2
b = B()
print b.get_value()
gives 1, but not 2. Thanks for your help.
Your problem is that double underscores are special in python, and create some modicum of privacy (not enforced, but it mangles the names, which is what is affecting you here). You should recreate this without the variable being named with double underscores. Also, you should use
superinstead of callingA.__init__explicitly:For more specifics if you don’t want to read the referenced documentation:
If you read the link on “special” above, that paragraph describes the internal name mangling that happens when you use
__. The short answer is thatA.get_value()returns_A__value, and settingself.__valueinBactually sets a member variable named_B__value, which means thatA.get_value()never sees it.You can prove this to yourself by indeed doing something truly hinky: