473,322 Members | 1,494 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

class MyList(list): Is this ok?

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
"""
Jul 18 '05 #1
3 1253
On Tue, 6 Jul 2004, Martin Bless wrote:
import csv,sys

class ColumnCollector(list):

def __init__(self):
self.sums = []
list.__init__(self) #1
This is perfectly acceptable, though the new-style way to do this is with
the slightly messier line:
super(ColumnCollector,self).__init__()
def append(self, v, calc=None):
list.append(self,v) #2


Same applies here:
super(ColumnCollector,self).append(v)

What you have now though is effectively the same thing as using the
super() calls.

Jul 18 '05 #2
m.*****@gmx.de (Martin Bless) wrote in
news:40***************@news.versatel.de:
Do I need line #1?
Practically, no you don't although it is cleaner if you do. The list
initialiser would be needed if you were allowing a non-empty list to be
created.

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 ...

In general:

self.method(parms)

can be regarded as shorthand for:

type(self).method(self, parms)

So, if you called "self.append(v)" this would be the same as calling
"ColumnCollector.append(self, v)" which as you noticed creates an infinite
loop. You need to force the call to happen on the base class, which means
you can't use the shorthand form.

There are two ways to force a call to act on a baseclass method. The usual
way is what you came up with, just name the baseclass explicitly:

list.append(self, v)

The other way is to use the super builtin:

super(ColumnCollector, self).append(self, v)

Using super ensures that the code will continue to work if anyone starts
trying to multiply inherit from both your class and another class
inheriting from list. However, unless you wrote your class with that usage
in mind the extra complexity is not usually worthwhile (and besides,
something else would almost certainly break).
Jul 18 '05 #3
Duncan Booth <du**********@suttoncourtenay.org.uk> wrote in
<Xn***************************@127.0.0.1>:
In general:

self.method(parms)

can be regarded as shorthand for:

type(self).method(self, parms)
Aah, that's it. Thanks.
The other way is to use the super builtin:

super(ColumnCollector, self).append(self, v)


Ok, I'll have to learn more about super().

Thank you,

Martin

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Michele Simionato | last post by:
Let me show first how does it work for tuples: >>> class MyTuple(tuple): .... def __new__(cls,strng): # implicit conversion string of ints => tuple .... return...
8
by: JustSomeGuy | last post by:
I need to write an new class derived from the list class. This class stores data in the list to the disk if an object that is added to the list is over 1K in size. What methods of the std stl...
2
by: '[] WiRaN | last post by:
I all, I need a classroom equivalent the "Class List" of c++, necessary to recoup given of some hands tanks, Bruno
10
by: Andrew McLellan | last post by:
I think I must be missing something about generics, perhaps just about the syntax. I'd like to derive a class MyList from System.Collections.Generic so that it can only contain instance of MyItem....
1
by: Kivak Wolf | last post by:
This is one GREAT resource made by Microsoft. http://beta.asp.net/QUICKSTART/util/classbrowser.aspx Check it out! Kivak Wolf
2
by: BBM | last post by:
I have the following base class that uses Generics in its definition. MyList(of T, C) - T is a BindingList(Of C), C is the type in the list I have many implemented classes...
2
by: Christian Chrismann | last post by:
Hi, an application uses a wrapper class for an STL list. Basically, this template class provides the same functions (delete, append, find...) as an ordinary STL list. Additionally, there are...
15
by: jayesah | last post by:
Hi All, List and its iterator work as following way : list<intmylist; list<int>::iterator itr; itr = mylist.begin(); cout << (*itr); But I want something like this:
0
by: Laurent.LAFFONT-ST | last post by:
Hi, I want to get all classes of a module in a list. I wrote this code but I wonder if there's not a simpler solution import inspect def getClassList(aModule):
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.