Instance of inherited nested class in outer class not allowed?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Feb 27 20:57:50 CET 2008


En Wed, 27 Feb 2008 16:52:57 -0200, mrstephengross  
<mrstevegross at gmail.com> escribi�:

>> 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.
>
> Hmmm. Well, I see why that works. It's too bad, though. If I want to
> keep all executed code safely within a "if __name__ == '__main__'"
> block, it ends up a bit ugly. Then again, I guess this is just an
> aspect of python I'll have to get used to. Is there a specific reason
> it works this way, by chance?

class statements (and def, and almost everything in Python) are  
*executable* statements, not declarations.
When you import a module, it is executed. If it contains a class  
statement, it is executed as follows: create an empty namespace (a dict),  
execute the class body in it, create a new class object with __dict__ =  
that namespace, and finally, bind the class name to the newly created  
class object in the module namespace.
Until that last step, you can't refer to the class being created by name.

I don't get your issue with "if __name__==__main__", but I hope that you  
now understand a bit better why a late initialization is required. (Of  
course someone could come up with a metaclass to perform that late  
initialization, but the important thing is to understand that you cannot  
create an instance before the class itself exists)

-- 
Gabriel Genellina




More information about the Python-list mailing list