[Tutor] subclass
Christopher Spears
cspears2002 at yahoo.com
Fri Feb 3 17:43:28 CET 2006
Here is a problem I'm working on out of Learning
Python:
Make a subclass of MyList from exercise 2 called
MyListSub which extends MyList to print a message to
stdout before each overloaded operation is called and
counts the number of calls. MyListSub should inherit
basic method behavoir from MyList. Adding a sequence
to a MyListSub should print a message, increment the
counter for + calls, and perform the superclass's
method.
There is more after that, but I will tackle that after
I clear up this part. Here is MyList.py:
class MyList:
def __init__(self, start):
self.mylist = []
for x in start: self.mylist.append(x)
def __getitem__(self, index):
return self.mylist[index]
def __setitem__(self, index, value):
self.mylist[index] = value
def __len__(self):
return len(self.mylist)
def __delitem__(self, index):
del self.mylist[index]
def __add__(self, other):
return MyList(self.mylist + other)
def __mul__(self, other):
return MyList(self.mylist * other)
def __getslice__(self, low, high):
return MyList(self.mylist[low:high])
def __repr__(self):
return '%s' % self.mylist
def append(self, other):
self.mylist.append(other)
def count(self, value):
return self.mylist.count(value)
def index(self, value):
return self.mylist.index(value)
def extend(self, seq):
self.mylist.extend(seq)
def insert(self, index, value):
self.mylist.insert(index, value)
def pop(self, index):
return self.mylist.pop(index)
def remove(self, value):
self.mylist.remove(value)
def reverse(self):
self.mylist.reverse()
def sort(self):
self.mylist.sort()
My first thought for printing messages was to do
something like this:
MyListSub.py:
from MyList import *
class MyListSub(MyList):
def __init__(self, start):
print "implementing __init__ method for MyListSub"
self.mylist = []
for x in start: self.mylist.append(x)
This is what I call the idiot's method. Basically, I
would put a print message in each method as well as
some sort of counter.
However, I keep wondering if there is a more elegant
way to do this like create some sort of function that
does this:
if a method is called:
print a message
if a method is called:
increment a counter for that method
More information about the Tutor
mailing list