Nested class structures

OKB (not okblacke) BrenBarn at aol.com
Sat Sep 11 12:27:51 EDT 2004


Alex Martelli wrote:
>>>> 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
>>>> 
>
>> 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. 

    	Well, I'm still experimenting with it, and partly I'm just playing 
around, but one possible thing I thought might come out of these nested 
classes is the ability to define a GUI with a syntax that mirrors the 
GUI's nested structure.  So each class in the tree there would represent 
some GUI component, and as the classes are created, some metaclass 
tinkering instantiates them, massaging information from the class def 
into the format required by the GUI library.

    	As far as the anonymous business, I'm beginning to think it may not 
be that much of a necessity, but: the idea is, suppose I'm defining a 
whole bunch of GUI objects like sizers or something.  It's tiresome to 
have to make sure they all have unique names, so I was hoping I could 
create some Python code that would generate the names for me.

    	Your code, of course, works great, but I am interested in subsuming 
the list creation and appending into the class definitions themselves, 
to avoid writing "anons.append(anon)" a bunch of times.  However, there 
doesn't seem to be any way for the metaclass of a nested class to get at 
the enclosing class namespace.  In fact, after looking at the docs some 
more, I see that this is an explicit exception to the normal scoping 
rules.  (The silver lining, though, is that it means I DON'T have to 
come up with totally unique names: they only have to be unique within a 
single enclosing class def, which makes it less of a burden to name the 
classes explicitly.)

    	Anyway, thanks for the help, everyone!

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
	--author unknown



More information about the Python-list mailing list