[Tutor] Restricting the type of passed-in objects
VanL
van@lindbergs.org
Fri, 11 May 2001 17:52:12 -0600
Hello all,
I am working on implementing a tree.
First I am going to do it as a class. A tree would be defined as one or
more treenodes.
My constructor looks like this:
class TreeNode:
def __init__(self, name=None, data=None, objparent=None,
childobjects=[]):
if name: self.__label = name
if data: self.__data = data
if objparent: self.__parentlink = objparent
if childobjects: self.__childrenlist = childobjects
Now here is my quandry: I think that I would want to restrict the type
of passed-in childobjects. In my way of thinking, anyone who wanted a
tree could either use the vanilla class or they could subclass
TreeNode. Ideally, then, the only objects passed in (as parents or
children, with the possible exception of the parent to the root node)
would be TreeNode instances (or whatever the subclass is).
However, what is to stop someone from saying:
>>> mytree = Tree.TreeNode('myname', 'mydata', 'myparent', 'mychildren')
All the children (and the parent too, in this case) would be set to
strings. Some methods of TreeNode might fail because they assume too
much about the nature of the children.
Now, I could do a bunch of testing on the children before calling them,
but that seems inelegant. I looked at the module 'types', but that
didn't seem to solve the problem:
>>> type(mytree)
<type 'instance'>
Any instance of any class would pass that test.
What can I do?
Alternatively, am I thinking about this in the wrong way? Do I *really*
want to restrict the accepted types? If I do, how can I structure this
thing?
Thanks,
Van