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

DBak davidbak at gmail.com
Fri Mar 7 16:00:53 EST 2008


I want - but cannot get - a nested class to inherit from an outer
class.  (I searched the newsgroup and the web for this, couldn't find
anything - if I missed an answer to this please let me know!)

I would like to build a class for a data structure such that nodes of
the data structure - of interest only to the data structure
implementation itself and not to the consumer - are instances of one
of two class types.  I thought to encapsulate the nodes' classes like
this:

class Tree(object):
...class _MT(Tree):
......def isEmpty(self): return True
......def insert(self, X): return Tree._Node(X)
...class _Node(Tree):
......def isEmpty(self): return False
......def insert(self, X): return _Node(X, self, Tree._MT())
...def merge(self, T):
......def __init__(): return _MT()
......<code for merging tree T into self>

In other words, some methods would be implemented on instances'
classes (like isEmpty and insert) and some on the outer class (like
merge).  Users of the data structure never need to know about the
nodes, much less the nodes' classes, so I wanted to encapsulate them

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.

What is the Pythonic thing I should be doing instead?

(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.)

Thanks! -- David



More information about the Python-list mailing list