Instance of inherited nested class in outer class not allowed?

Diez B. Roggisch deets at nospam.web.de
Wed Feb 27 13:29:08 EST 2008


mrstephengross schrieb:
> I've got an interesting problem with my class hierarchy. I have an
> outer class, in which two nested classes are defined:
> 
> class Outer:
>   class Parent:
>     def __init__ (self):
>       print "parent!"
>   class Child(Parent):
>     def __init__ (self):
>       Outer.Parent.__init__(self)
>   foo = Child()
> 
> Note that the second nested class (Outer.Child) inherits from the
> first nested class (Outer.Parent). When I run the above code, python
> reports a name error:
> 
> Traceback (most recent call last):
>   File "./temp.py", line 3, in ?
>     class Outer:
>   File "./temp.py", line 13, in Outer
>     foo = Child()
>   File "./temp.py", line 11, in __init__
>     Outer.Parent.__init__(self)
> NameError: global name 'Outer' is not defined
> 
> Apparently, python doesn't like having an instance of a derived nested
> class present in the outer class. Interestingly enough, if I change
> the foo variable to an instance of the parent class:
> 
>   foo = Parent()
> 
> everything is hunky-dory. Is there some syntax rule I'm breaking here?

It's simple - you try to refer to Outer whilst Outer itself is being 
created. A much simpler version of your problem is this:


class Foo:
      foo = Foo()

You have to live with that. Just do

Outer.foo = Outer.Parent()

after your class-statement to achieve the same result.

Diez



More information about the Python-list mailing list