[Tutor] Defining a new class
VanL
tutor@python.org" <tutor@python.org
Mon, 19 Mar 2001 22:35:42 -0700
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
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)
I'm a little confused about that. I'm calling a function, aren't I?
Still, after a little checking, I found
>>> print Me.label
MyName
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>
Similarly,
>>> print (MyFriend.next).label
should return
MyName
Instead, it returns
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: label
Also,
>>> print MyFriend.next
<method LinkedList.next of LinkedList instance at 0082D65C>
seems to show that I am not even getting back to my original node
"Me".
Could anyone enlighten me?
Thanks very much,
Van