[Tutor] Defining a new class
D-Man
dsh8290@rit.edu
Tue, 20 Mar 2001 16:14:41 -0500
On Mon, Mar 19, 2001 at 10:35:42PM -0700, VanL wrote:
| Hello,
|
| I am just getting started with Python so I thought I would implement
| a lot of the classical data structures in Python so as to get a feel
| for it. I am running into a few difficulties, tho. Here is my
| first Python class:
|
| class LinkedList:
|
| def __init__(self, name, object=None):
| self.label = name
| if object: self.link = object
| else: self.link = None
I just want to ask why you check the value of 'object' here? If the
client doesn't give a value for object it will be None, which is what
you set it to in the else clause. I think that the following will be
semantically equivalent to what you want:
def __init__( self , name , object=None ) :
self.label = name
self.link = object
|
| def next(self):
| if self.link: return link
| else: return None
same here. self.link will already be None, so why return None
explictly? Another consideration : if you provide a function such as
is_last() or has_next() that will indicate whether or not there is
another node in the list, this function can throw an exception when
there is nothing left in the list.
I don't think perl has exceptions, so your Perl book probably uses a
C-like setinel return value to indicate an error (null , None , etc).
Python has exceptions which make error handling much nicer and easier.
(if you want some more info/examles using exception just holler, or
check the archives of this and python-list for messages from me (they
center around raw_input and converting to a number))
| def label(self):
| return self.label
|
| def link(self, object):
| self.link = object
|
| def unlink(self):
| self.link = None
|
| def rename(self, name):
| self.label = name
|
|
| Some things work as expected; I can declare an object of type
| LinkedList. I get some strange results overall, tho. For example:
I'll assume you have already corrected these from everyone else's
responses ;-).
| Thanks very much,
|
| Van