[Tutor] Defining a new class

Remco Gerlich scarblac@pino.selwerd.nl
Tue, 20 Mar 2001 08:53:25 +0100


On Mon, Mar 19, 2001 at 10:35:42PM -0700, VanL wrote:
> 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
> 
>     def next(self):
>         if self.link: return link
>         else: return None
> 
>     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:
> 
> >>> from LinkedList import *
> >>> dir(LinkedList)
> ['__doc__', '__init__', '__module__', 'label', 'link', 'next',
> 'rename', 'unlink']
> 
> So far so good.
> 
> >>> Me = LinkedList('MyName')
> >>> MyFriend = LinkedList('HisName', Me)
> >>> print Me.label()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: call of non-function (type string)

Your function is called label, then in your __init__ you make a variable of
the same name... 'Me.label' looks for 'label' in the instance first (finds
the variable) and only if it finds nothing will it go look in the class to
see if it has a 'label'. So, indeed, Me.label is a string, not a function,
and you can't call it.

> Still, I am confused.  Moreover, the next function isn't working as
> I expected. I thought that
> >>> print Me.next
> 
> should return
> 
> None
> 
> Instead, it returns
> 
> <method LinkedList.next of LinkedList instance at 0082A45C>

Me.next is simply the method (you didn't overwrite that name). So you can
call it, ie you're looking for 'Me.next()'.

I find I never use linked lists in Python by the way, always just Python
lists. And so many other standard hard algorithms and data structures become
trivial when you have dictionaries available :).

-- 
Remco Gerlich