[Tutor] help with refactoring needed -- which approach ismorePythonic?

Alan Gauld alan.gauld at freenet.co.uk
Fri Feb 11 19:51:19 CET 2005

> My Example Body
>     Node List
>        Node the first
>        Node the second
> Is there any way to make methods of the Node class access attributes
> of `parents' of instances? I would like a Node instance such as Node
> the first above to be aware just what it is a node of and what its
> siblings are.

Pass a reference to the container into the constructor of Node

class Body:
      def parse(self):
          for line in self.contents:
              if line == NodeStartTag:
                 node = Node(self)
              if line == NodeEndTag:

And modify the Node constructor to accept and assign the value
to self.parent.  This is the same approach used in Tkinter to
navigate between GUI components such as buttons and theor
containing frame.

(And to pick up on someone else's question this is why you should
put in a __del__ to tidy up the Node list when Body is destructed
- otherwise you get circular references which can cause memory
leaks by confusing the garbage collector!


Alan G.

More information about the Tutor mailing list