[Tutor] Learning Python
Grigor Kolev
grigor.kolev at gmail.com
Sun Dec 13 13:36:26 CET 2009
It is from book Learning Python
--------------------------------------------
Operator overloading. Write a class called Mylist that shadows (“wraps”)
a Python
list: it should overload most list operators and operations, including
+, indexing,
iteration, slicing, and list methods such as append and sort. See the
Python
reference manual for a list of all possible methods to support. Also,
provide a con-
structor for your class that takes an existing list (or a Mylist
instance) and copies
its components into an instance member. Experiment with your class
interac-
tively. Things to explore:
a. Why is copying the initial value important here?
b. Can you use an empty slice (e.g., start[:]) to copy the initial
value if it’s a
Mylist instance?
c. Is there a general way to route list method calls to the wrapped
list?
d. Can you add a Mylist and a regular list? How about a list and a
Mylist
instance?
e. What type of object should operations like + and slicing return? What
about
indexing operations?
f. If you are working with a more recent Python release (version 2.2 or
later),
you may implement this sort of wrapper class by embedding a real list
in a
standalone class, or by extending the built-in list type with a
subclass.
Which is easier, and why?
----------------------------------------------------
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
------------------------------------------------------
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
--
Grigor Kolev <grigor.kolev at gmail.com>
More information about the Tutor
mailing list