class MyList(list): Is this ok?

Martin Bless m.bless at gmx.de
Tue Jul 6 14:36:25 CEST 2004


Please have a look at my little program below. It works as expected
but I still feel very unsure when inheriting from builtin types.

Do I need line #1?

Is line #2 ok? Why? I came to this one more by trial and error than by
conclusion. My fingers wanted to write "self.append(v)" which creates
a nice infinite loop ...

I have read the article about "Unifying types and classes" by GvR
http://www.python.org/2.2/descrintro.html several times but probably
would need more practical examples or another tutorial.

Martin



import csv,sys

class ColumnCollector(list):

    def __init__(self):
        self.sums = []
        list.__init__(self)         #1

    def append(self, v, calc=None):
        list.append(self,v)         #2
        i = len(self)-1
        try:
            self.sums[i]
        except IndexError:
            self.sums.append(0)
        if calc:
            if "sum" in calc:
                self.sums[i] += v

if 1 and __name__=="__main__":
    print
    csvw = csv.writer(sys.stdout)
    cc = ColumnCollector()
    for rownum in range(4):
        cc.append(1,"sum")
        cc.append(2,"sum")
        cc.append(3,"sum")
        csvw.writerow(cc)
        del cc[:]
    print "totals:"
    csvw.writerow(cc.sums)
""" Should print:
1,2,3
1,2,3
1,2,3
1,2,3
totals:
4,8,12
"""





More information about the Python-list mailing list