inner classes in python as inner classes in Java

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Oct 16 04:30:06 EDT 2003


"Carlo v. Dango" <oest at soetu.eu> wrote in
news:oprw4lztsdmyya52 at news.kadnet.dom: 

>> You'll have to decide what semantics you want to obtain when an
>> attribute is set on an instance of the "inner class" -- I sure can't
>> do it on your behalf.
> 
> I want the semantics of java's inner classes and the semantics of
> inner methods... that the inner class shares the fields and methods of
> its outer class instance.. But I've come to realize I can't do this in
> python, as the statement in some method in the inner class "self.i =
> 42" can be interpreted as "create i in the inner class instance" or
> "lookup i in the 'outer scope' and set it"

What you want wouldn't necessarily be impossible. You should be able to 
create a metaclass for the inner class that automatically creates 
properties in the inner class which access the outer class fields. That way 
you could expand:

    self.a = 42

to something equivalent to:

   self.__outer.a = 42

Actually, thinking about it you need to put the metaclass on the outer 
class rather than the inner one. That way when the outer class is created, 
you can check its dictionary for any classes it contains and give each of 
those classes the appropriate properties.

I think it ought also to be possible to add a __get__ method to the inner 
class so that accessing the inner class through an instance of the outer 
class returns what would effectively be a 'bound class' (cf bound method) 
which sets the __outer member automatically when you create an instance of 
the inner class.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list