Inner classes

Samuele Pedroni pedroni at inf.ethz.ch
Wed Jun 13 22:25:37 CEST 2001


Bjorn Pettersen wrote:

> > From: Samuele Pedroni [mailto:pedroni at inf.ethz.ch]
> >
> > Andrew Kuchling wrote:
> >
> > > xyzmats at laplaza.org (Mats Wichmann) writes:
> > > > Nonetheless, I was challenged by someone to describe how
> > it isn't a
> > > > shorcoming in Python that classes don't work this way and didn't
> > > > convince the guy so I'm looking for a more erudite comparison.
> > >
> > > Work *what* way?  It's perfectly legal to do this:
> > >
> > > 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)
>
> Not true...
>
>   from __future__ import nested_scopes
>
>   class Outer:
>     def foo(self):
>       class inner:
>         def bar(this):
>           self.foo()
>           this.bar()
>
> bar can now reference both it's own class (inner) and the Outer class.
> Not that this code is doing anything particularly useful though <wink>.
>
> -- bjorn

You're right, let it turn it in a useful pattern <wink>:

from __future__ import nested_scopes

class Outer:
    def inner(self):
      class _inner:
        def bar(this):
          self.foo()
          this.bar()
      return _inner()

now Outer().inner() will work (but being inner a factory and not a class
will defeat introspection).

regards.





More information about the Python-list mailing list