Nested class structures

Russell Blau russblau at hotmail.com
Fri Sep 10 16:43:05 EDT 2004


"OKB (not okblacke)" <BrenBarn at aol.com> wrote in message
news:Xns95607B54E1208OKB at 130.133.1.4...
>     For a variety of reasons, I'm interested in putting together some
> code that will allow me to created structures out of nested classes,
> something like:
>
> class class1:
>     def methA(self):
>         print "Some code here"
>     class class2:
>         propA = "A"
>         def methB(self):
>             print "Some more code here"
>     class class3:
>         # etc.
>         class class4:
>             pass
>             #etc
>
>     The main problem is that Python does not seem to provide enough
> information about the lexical context of definitions like this.  In
> particular, I would like the ability to have some of the nested classes
> be "anonymous" -- that is, I don't want to have to worry about choosing
> identifiers for them.  I'd LIKE to do this:
>
> class class1:
>     class anon: pass
>     class anon: pass
>     class anon: pass
>
>     . . . and somehow intercept or monitor the name-binding that's
> going on there so I wind up with three separate classes which are bound
> to uniquely named attributes of class1.  But I can't do this because
> each anon stomps on the previous name binding, and there doesn't seem to
> be a way to intervene and bind a new attribute in class1, because class1
> isn't really created until after all the nested class definitions
> happen.

I don't really understand what it is you are trying to do, but...

you can create an "anonymous" class object with:

type("anon", (object,), {})

This returns an object that is functionally identical to the object created
by:

class anon(object):
    pass

Of course, you'll need to store the returned object somewhere to do anything
useful with it.


-- 
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.





More information about the Python-list mailing list