Nested class structures

Alex Martelli aleaxit at yahoo.com
Sat Sep 11 09:34:19 EDT 2004


Diez B. Roggisch <deetsNOSPAM at web.de> wrote:
   ...
> The only thing that comes to my mind is to create the classes from strings
> you exec - that will allow you to captur the class before redefining it:

You can capture before redefining without any need to exec:

>>> class outside:
...   anons=[]
...   class anon:
...     def method1(self): return 'the first'
...   anons.append(anon)
...   class anon:
...     def method1(self): return 'the second'
...   anons.append(anon)
...   class anon:
...     def method1(self): return 'the third' 
...   anons.append(anon)
...   del anon
... 
>>> for c in outside.anons: print c().method1()
... 
the first
the second
the third
>>> 


> Apart from that, I don't see any way to accomplish this - and for good
> reasons: classes as well as functions are only declarations - that means

No way!  Classes as well as functions are perfectly fine objects.
Python has no 'declarations'.

> that they are stored in a sort of symbol table. And as there is no such
> thing like an order of declartions, the only thing to access them is their

These is no such thing as "an order of declarations" because there are
no such things as declarations.  There are statements, and of course
there is an order of them, including the two, def and class, most
popularly used to create functions and classes respectively.

Generally, Python collects names and their correspondence to objects in
a dictionary, and a dictionary indeed has no ordering, so there is no
trace left of the order in which the names were added to the dictionary
(except that a name->value correspondence added later tramples over any
that might have been added earlier for that same name). Which is why I'm
using a list, and calls to its append method, in the above example.


> The question is: _why_ do you want to do this? How do you want to access the

That is indeed totally mysterious to me.  I have a decent grasp of what
can be done, but sometimes the deeper question of why anybody might ever
possibly want to do it escapes me totally, and this is such a case.


Alex



More information about the Python-list mailing list