Errors in web2py book

2 views
Skip to first unread message

guruyaya

unread,
Sep 12, 2010, 10:40:26 PM9/12/10
to web2py-users
In chapter 2, on the code example of "Special Attributes, Methods and
Operators", we have

class MyList(object)
def __init__(self, *a): self.a = a
def __len__(self): return len(self.a)
def __getitem__(self, i): return self.a[i]
def __setitem__(self, i, j): self.a[i] = j
b = MyList(3, 4, 5)
print b[1]
a[1] = 7
print b.a

1. The first line should be
class MyList(object):

2. Running line 9 of the code produces this exception:
>>> a[1] = 7
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

I'm not sure what was intended to be demonstrated there, as even b[1]
= 7 produces an excption, but it's not working.

b vivek

unread,
Sep 12, 2010, 11:06:44 PM9/12/10
to web...@googlegroups.com
Use this:-

class MyList(object):
    def __init__(self, *a): self.a = list(a)#this has to be a list, was a tuple earlier
    def __len__(self): return len(self.a)
    def __getitem__(self, i): return self.a[i]
    def __setitem__(self, i, j): self.a[i] = j
b=MyList(3,4,5)
print b[1]
b[1]=7#self-explanatory
print b.a

guruyaya

unread,
Sep 13, 2010, 1:08:56 AM9/13/10
to web2py-users
That's awsome, but it does not explain getitem. Maybe it should be:
class MyList(object):
def __init__(self, *a): self.a = list(a)
def __len__(self): return len(self.a)
def __getitem__(self, i): return self.a[i]
def __setitem__(self, i, j): self.a[i] = j

b=MyList(3,4,5)
print b[1]
b[1]=7
print b[0]

On Sep 13, 5:06 am, b vivek <bvivek1...@gmail.com> wrote:
> Use this:-
>
> class MyList(object):
>     def __init__(self, *a): self.a = list(a)#this has to be a list, was a
> tuple earlier
>     def __len__(self): return len(self.a)
>     def __getitem__(self, i): return self.a[i]
>     def __setitem__(self, i, j): self.a[i] = j
> b=MyList(3,4,5)
> print b[1]
> b[1]=7#self-explanatory
> print b.a
>
Reply all
Reply to author
Forward
0 new messages