Question

Need a way to indicate/enforce that certain methods can only be done on the root Node of my tree data structure. I'm working in Python 2.x

I have a class, Node, which I use in conjunction with another class, Edge, to build a tree data structure (edges are letters and nodes are words, in this case).

Some methods in Node are needed for every instance of the Node, like get_word, which runs backwards through the tree to determine the word being represented by that Node. But other Node operations, like load_word_into_tree, seem more like a class methods -- they operate on the entire tree. Furthermore, the way I have structured the that call, it requires the root node and the root node only as its input. If it is called on any other node, it'll totally mess up the tree.

I see two options:

  • Make load_word_into_tree an instance method, but raise an error if it is called on any Node that isn't the root. I'm leaning towards this, but something just seems not right about it. In my mind, instance methods are methods that every instance should need, and to have this method tacked on to every Node when it can only ever be used for the root seems like a waste.

  • Make load_word_into_tree a class method, but pass it the root node as an arg. This gets around the problem of a 'wasteful' instance method, but also seems like a misuse of concept of a class method, since it takes a single node as its input. Furthermore, I'm not sure what use I'd have for the required cls variable available to every class method.

Any help on where and how to implement this function would be greatly appreciated.

Was it helpful?

Solution

Make a Tree subclass of Node and add the tree-only methods on that class instead.

Then make your root an instance of Tree, the rest of your graph uses Node instances.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top