Class Inheritance - What am I doing wrong?
Arnaud Delobelle
arnodel at googlemail.com
Thu Apr 24 16:43:28 EDT 2008
Brian Munroe <brian.e.munroe at gmail.com> writes:
> My example:
>
> class A(object):
>
> def __init__(self, name):
> self.__name = name
>
> def getName(self):
> return self.__name
>
> class B(A):
>
> def __init__(self,name=None):
> super(A,self).__init__()
>
> def setName(self, name):
> self.__name = name
>
> if __name__ == '__main__':
>
> a = A('class a')
> print a.getName()
>
> b = B('class b')
> print b.getName()
>
> b.setName('class b, reset')
> print b.getName()
>
> I get the following error:
>
> mtinky:~ brian$ python teste.py
> class a
> Traceback (most recent call last):
> File "teste.py", line 23, in <module>
> print b.getName()
> File "teste.py", line 7, in getName
> return self.__name
> AttributeError: 'B' object has no attribute '_A__name'
>
> Am I *not* using super() correctly? Also, did I define my the class B
> constructor correctly?
You have fallen victim to the Name Mangling Trap [1]. Replace the
leading double underscore in the __name attribute with a single one,
and Python shall calm down and let your code behave as you expect it
to.
That is, if you also pass the name parameter to super(A,self).__init__
in B's __init__ method
[1] http://docs.python.org/ref/atom-identifiers.html
--
Arnaud
More information about the Python-list
mailing list