Newbie question about nested lists and constructor functions...
Chris Gonnerman
chris.gonnerman at usa.net
Mon Mar 5 00:24:10 EST 2001
----- Original Message -----
From: "Norm Lyons" <norm at cybersurf.net>
Sent: Sunday, March 04, 2001 10:18 PM
Subject: Re: Newbie question about nested lists and constructor functions...
> Sorry about that Chris.
S'awright.
> I am trying to create instantiated objects with the following properties:
>
> list_var = [(key, value), left, right]
>
> where the "key, value" pair are a tuple, and the variables "left" and
> "right" are empty lists [ ] which will be manipulated to hold values later
> in the program after they have already been initialized to empty lists.
The
> purpose of this object is to hold the necessary data for nodes in a binary
> search tree. I know how to implement this type of data structure in C++
but
> I seem to be getting hung up on the syntax differences in the Python class
> and member variable declarations.
>
> An example of one of my attempts would be:
>
> class Node:
> def __init__(self, key = ''):
> left = []
> right = []
> data = (key, 'value')
> newnode = [data, left, right]
> def info(self):
> return self.data
OKAY. Now we are getting somewhere. This seems to be a common mistake for
users of other languages. Your code likely should be like this:
class Node:
def __init__(self, key = ''):
left = []
right = []
data = (key, 'value')
self.data = [data, left, right]
def info(self):
return self.data[0]
SPECIFICALLY, you need to assign your list to a data attribute of self. I
would write
your code more like this:
class Node:
def __init__(self, key = ''):
self.left = []
self.right = []
self.data = (key, 'value')
def info(self): # not really needed with this version IMHO
return self.data
or perhaps:
class Node:
def __init__(self, key = '', value = ''):
self.left = None # these get object references (later)
self.right = None # so I don't think they need to be lists.
self.key = key
self.value = value # is this a default?
def info(self): # not really needed with this version IMHO
return (self.key, self.value)
but that is a personal thing.
> The "info" function is only intended to return the values of the variables
> "key and value". The other values are used as pointers to child nodes in
> the tree. As I mentioned earlier, I have been through the online tutorial
a
> few times and have not found any information that clears this issue up for
> me. Obviously, the code above is incomplete as it should also contain the
> appropriate "if" and "elif" statements to properly branch according to the
> information passed to the constructor function. Unfortunately, I do not
> know what I am doing wrong. Any suggestions?
I think I have this all right, but I haven't test run it yet. Good luck :-)
More information about the Python-list
mailing list