[Tutor] re: VanL LinkedList
John Thingstad
jthing@frisurf.no
Tue, 20 Mar 2001 14:42:14 +0100
You wrote:
>class LinkedList:
> def __init__(self, name, object=None):
> self.label = name
> i f 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
First the obvious. In function next you wrote: if self.link: return link
link is the class method link. You meant self.link.
Next is the scoping issue that is giving you trouble.
You have both a class variable that is named label and a function that is named label.
The label function is declared as local to the class. The variable self.label, however, belongs to the object instance and thus takes presedence
You get the same problem with link.
The nobrains solution is to rename the instance variables __label and __link.
the __ extension up front means they are private (well, almost private) to the class.
Not only does that better present the abstraction but it resolves the name conflict.
The result is what you see below. It works fine.
Given that lists are built into Python, and much more powerfull than this besides, it is of cource a pointless class.
But then you probably know this.
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 self.__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