Want - but cannot get - a nested class to inherit from outer class
arkanes at gmail.com
Fri Mar 7 22:19:55 CET 2008
On Fri, Mar 7, 2008 at 3:00 PM, DBak <davidbak at gmail.com> wrote:
> 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
> 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.
Not only is the name not defined, the class doesn't even exist yet.
> 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.
> (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 *".
More information about the Python-list