[Tutor] Class Inheritance -> NameError

John Fouhy john at fouhy.net
Thu Dec 1 05:11:12 CET 2005

On 01/12/05, Tim Johnson <tim at johnsons-web.com> wrote:
> My thanks to Christopher and Liam. I've revisited this
> with the following:
> class test:
>     def __init__(self):
>         self.s = ' there'
>     def val(self,V):
>         print '%s%s' % (V,self.s)
> class sub(test):
>     def __init__(self):
>         pass
> The following console session:
> >>> T = mylib.test()
> >>> S = mylib.sub()
> >>> S.val('hello')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "mylib.py", line 1609, in val
>     print '%s%s' % (V,self.s)
> AttributeError: sub instance has no attribute 's'

Hi Tim,

When you create an instance of a class, python calls the __init__
method of the class you just created, but it _doesn't_ call the
__init__ method of any superclasses.  There are several good reasons
for this --- it doesn't know what parameters you want to pass to the
superclass __init__ methods, or when you want to call them.  So, it is
up to you to make that call.

You can do that like this:

class sub(test):
  def __init__(self):

Because self.s is only created in test.__init__, you have to call the
__init__ method to get access to it.



More information about the Tutor mailing list