subclassing builtin types

Steven Bethard steven.bethard at gmail.com
Fri Oct 8 00:37:59 EDT 2004


BJörn Lindqvist <bjourne <at> gmail.com> writes:
> Take for example this class which
> is supposed to be a representation of a genome:
> 
> class Genome(list):
>     def __init__(self):
>         list.__init__(self)
>         self = ["A", "G", "C", "G", "A"]
>         ....
> 
> etc, you get the point. The line self = ["A", "G", "C", "G", "A"] will
> not work like I have intended.

This will not work as you intended because all you're doing is binding the 
name "self" to a new object.  When the method is called, self is bound to the 
object instance to be created.  When you assign to self, you bind it to some 
other object.  For comparision, consider the code:

>>> def f(lst):
...     lst = []
...
>>> l = [1, 2, 3]
>>> f(l)
>>> l
[1, 2, 3]

Hopefully, you didn't expect l to become the empty list?  The arguments to the 
__init__ method of a class work just the same as the arguments to any other 
method -- they're just names bound to objects.  Binding them to different 
objects does not change the original objects.

You want to do one of the following:

list.__init__(self, ["A", "G", "C", "G", "A"])

or

self.extend(["A", "G", "C", "G", "A"])


> There are quite a few other problems I
> can't solve too, but getting the [] operator right seems almost
> impossible.

I don't know what you mean by this?  Do you mean you can't index your list?  
(E.g. lst[0]).  Could you give an example of your problem here?

> Then I've asked around on IRC and the general consensus
> seem to be that subclassing buiiltin types is Not A Good Idea <TM>. 
> Why not?

I agree with this for some classes.  I think there is very little call for 
subclassing, say, int.  But I know I've subclassed dict a couple of times to 
do useful things like allowing only one entry per key, etc.

> Why is it so much harder in Python?

It's not, if you understand name binding. ;)

Steve






More information about the Python-list mailing list