Class Inheritance - What am I doing wrong?

Gary Herron gherron at islandtraining.com
Thu Apr 24 16:54:29 EDT 2008


Brian Munroe wrote:
> 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?
> --
> http://mail.python.org/mailman/listinfo/python-list
>   

Tell us what you are trying to do and what you expected to happen. 

If you are trying to do simple inheritance, you don't need the supers, 
and you should not invoke the name mangling implied by the double 
underscore.

If you *are* trying to use the name mangling, then you still don't need 
the super.


Gary Herron





More information about the Python-list mailing list