class MyList(list): Is this ok?

Duncan Booth me at privacy.net
Tue Jul 6 09:17:35 EDT 2004


m.bless at gmx.de (Martin Bless) wrote in 
news:40ea99e8.20568968 at 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).



More information about the Python-list mailing list