[Tutor] Still on Linked Lists

alan.gauld@bt.com alan.gauld@bt.com
Wed, 4 Apr 2001 11:39:45 +0100


> class LinkedList2:
>     def __init__(self, name, data=None, object=None):
>         self = (name, data, object)

AArgh! This is a really bad idea. Never, ever, mess 
with self(OK, Never say never but...) self represents 
the instance itself thus you are trying to replace 
your object with a tuple! That's not smart.

Instead create an instance variable that holds the tuple:
          self.items = (name, data, object)

>     def next(self):
>          return self[2]

This won't work because self no longer exists as an object.
(Indeed you couldn't actually even call it!)

If you do as suggested above you need to rewrite the methods as:

     def next(self):
          return self.items[2]

> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "LinkedList2.py", line 32, in __str__
>     print self[0], self[1], self[2]
> AttributeError: 'LinkedList2' instance has no attribute '__getitem__'

If you really want to access self as a sequence you need 
to provide a __getitem__ method. Since you didn't the call 
fails.

You could have done:

     def __getitem__(self, i):
         return self.items[i]

And it might have worked - but I haven't tried... 
adding an instance variable is better IMO.

Alan G