Want - but cannot get - a nested class to inherit from outer class

DBak davidbak at gmail.com
Fri Mar 7 17:39:57 EST 2008


On Mar 7, 1:19 pm, "Chris Mellon" <arka... at gmail.com> wrote:
> On Fri, Mar 7, 2008 at 3:00 PM, DBak <david... at gmail.com> wrote:

> >  However I can't do this, because, of course, the name Tree isn't
> >  available at the time that the classes _MT and _Node are defined, so
> >  _MT and _Node can't inherit from Tree.
>
> Not only is the name not defined, the class doesn't even exist yet.

Yes, but, well - it certainly isn't usable yet, but some object (that
will be the class when it is finished) is being built (its __dict__ is
being populated, etc.) - so there's an object pointer available inside
the interpreter that could be put somewhere.  But this is pedantic -
you're right, the class really isn't available until after the class
statement.

> >  What is the Pythonic thing I should be doing instead?
>
> Don't nest them. The single underscore is all you need to keep any
> from using them (don't forget that even if your method worked, they'd
> be perfectly visible as attributes of the Tree class, or as the types
> of returned values). Worrying too much about visibility is a waste of
> time in Python.

Yes, I knew it wouldn't stop the determined coder from finding and
using them.

However, I did actually have a reason for wanted them nested:  I
wanted to put more than one similar data structure in the same source
file - and several of them would have "Empty" nodes that would behave
differently.  If I used nested classes all those classes could be
named Empty.  If flattened to module level then I'd have to invent
different names for each one, like, AVL_Empty, RedBlack_Empty, and it
wouldn't seem as "nice" (for some definition of "nice" that I have in
my head).

> >  (Easy answer:  Put this code in a module, exposing only a factory
> >  function.  I could do that, but wanted to know if I could encapsulate
> >  it as described so I could actually put several similar data
> >  structures into one module.)
>
> There's no reason to use a factory function. If you do put them in a
> module, you can use __all__ to document your exports. As with all
> visibility issues in Python, this is advisory only - the only code it
> affects is the symbols that are exported by "from module import *".

OK.

Thanks!  -- David



More information about the Python-list mailing list