M
Martin Bless
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
except IndexError:
self.sums.append(0)
if calc:
if "sum" in calc:
self.sums += 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
"""
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
except IndexError:
self.sums.append(0)
if calc:
if "sum" in calc:
self.sums += v
if 1 and __name__=="__main__":
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
"""