This is what I’m trying to do in Python:
class BaseClass:
def __init__(self):
print 'The base class constructor ran!'
self.__test = 42
class ChildClass(BaseClass):
def __init__(self):
print 'The child class constructor ran!'
BaseClass.__init__(self)
def doSomething(self):
print 'Test is: ', self.__test
test = ChildClass()
test.doSomething()
Which results in:
AttributeError: ChildClass instance has no attribute '_ChildClass__test'
What gives? Why doesn’t this work as I expect?
From python documentation:
So your attribute is not named __test but _BaseClass__test.
However you should not depend on that, use self._test instead and most python developers will know that the attribute is an internal part of the class, not the public interface.