[Tutor] variable inheritance

Alan Gauld alan.gauld at btinternet.com
Mon Mar 8 19:55:45 CET 2010


"spir" <denis.spir at gmail.com> wrote

> Say I have a Tree type that may be based on 2 kinds of Node-s.
> Both conceptually and practically, a tree itself is a node, namely the 
> top/root one.

Thats one way to do it...

> But a tree also has some additional tree-level behaviour, which is 
> independant
> of the kind of node.

In which case its possibly not a node because it may be breaking the
Liskov Substitution Principle. In that case a Tree has its own identity
and behaviour and attributes, one of which is a heirarchy of nodes.

So you must decide first of all; Is a tree really a node - ie is it fully
interchangable with a node?

Say, the node type performs all the underlying tree mechanics. Thus the 
Tree type looks like:
>
> class Tree(_Node):
>    def __init__(self, args):
>        _Node.__init__(self)
>        ...
>    ... tree-level methods ...
>
> The issue is the actual kind of node is not only initialised
> through "_Node.__init__(self)": it must first feature as super class
> in "class Tree(Node)".

Surely the different types of node are all subclasses of the
(possibly abstract) Node class? ie you have 3 subclasses
of Node?

> I tried to play with __new__ in Tree and Node types, but
> this error seems unavoidable. Maybe I did not do it right.

I'm not totally sure what you did to get the error?

> I can indeed have __new__ return an instance of either
> Node type, but then for any reason it "forgets" it is also
> a tree (so that calling any tree method fails).
> I there a way to do this right?

Provided the tree is not dependant on the node types
there should not be a problem. The Tree treats all nodes
as Nodes. Polymorphism should do the rest.

> Workaround ideas:
> * Make the root node an attribute of tree: unsatisfying.

Why is it unsatisfying? Its a perfectly legitimate model.
It is the one used by most GUI frameworks for the widget
containment tree

> * Create a common tree type and 2 specialised ones:
> class TreeN(Tree,NodeN)
>    def __init__(self, args):
>        _NodeN.__init__(self)
>        Tree.__init__(self, args)
> # ... e basta ...

Or a Common Node type and 3 subclasses, Tree,, Node1 and Node2

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list