[Tutor] Learning Python

Alan Gauld alan.gauld at btinternet.com
Sun Dec 13 18:06:33 CET 2009


"Grigor Kolev" <grigor.kolev at gmail.com> wrote

> ----------------------------------------------------
> My answer is:
> class MyList ():
> def __init__(self, value=[]):
> self.list=[]
> for i in value:
> self.list.append(i)
> def __add__(self , other):
> return self.list
> def __mul__(self , other):
> return self .list
> def __delitem__(self , other):
> return self .list
> def __geritem__(self , other):
> return self.list
> def __repeat__(self , other):
> return self.list
> def sort(self  ):
> self.list = self.list.sort()
> return self.list
> def append(self , other):
> self.list=self.list.append(other)
> return self.list
>
> This is work

Given that add does not add anything how do you define "work"?
Do you mean it executes without error messages?


> ------------------------------------------------------
> In the book answer is this:
>
> class MyList:
>  def _ _init_ _(self, start):
>        #self.wrapped = start[:]         # Copy start: no side effects
>        self.wrapped = []                # Make sure it's a list here
> for x in start: self.wrapped.append(x)
> def _ _add_ _(self, other):
> return MyList(self.wrapped + other)
> def _ _mul_ _(self, time):
> return MyList(self.wrapped * time)
> def _ _getitem_ _(self, offset):
> return self.wrapped[offset]
> def _ _len_ _(self):
> return len(self.wrapped)
> def _ _getslice_ _(self, low, high):
> return MyList(self.wrapped[low:high])
> def append(self, node):
> self.wrapped.append(node)
> def _ _getattr_ _(self, name):       # Other members: sort/reverse/etc
> return getattr(self.wrapped, name)
> def _ _repr_ _(self):
> return repr(self.wrapped)
>
> Answer in the book does not work
> Where is the error

What error do you get?
These merthods do entirely different things to yours.
But without an error description its hard to comment, I don't feel like
reading through line buy line trying to guess what the problem might be.

It will also help if you tell us which version of Python you are using and
which Operating System.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list