Inner classes

Alex Martelli aleaxit at yahoo.com
Wed Jun 13 17:42:48 EDT 2001


"Samuele Pedroni" <pedroni at inf.ethz.ch> wrote in message
news:3B27BE5F.4DCB4894 at inf.ethz.ch...
    ...
> > class C:
> >     class inner:
> >         ... stuff for inner class
> >     ... stuff for class C
> >
> > --amk
>
> Yes, but that's basically a static inner class, you can do
>
> C().inner() but the created inner instance will not contain any
> implicitly created reference to the C instance.
>
> To have that you must be explicit:
> c=C()
> i=C.inner(c)

Explicit is better than implicit, but it's absolutely no
problem to have client-code call C().inner() and have
the returned innerclass instance know about the C
instance that created it -- you just have to place your
explicitness in the classes in question, e.g.:

class C:
    class __inner:
        def __init__(self, c):
            self.c = c
        # add whatever else you want in inner
    def inner(self):
        return self.__inner(self)
    # add whatever else you want in C

>>> c=C().inner()
>>> c
<__main__.__inner instance at 0079B48C>
>>> c.c
<__main__.C instance at 0079C58C>
>>>


Alex






More information about the Python-list mailing list