Overriding UserList methods

David Bolen db3l at fitlinxx.com
Wed Mar 7 20:16:48 CET 2001


Daniel Klein <danielk at aracnet.com> writes:

> I found the answer in the Beazley book. It's
> 
> def append(self, object):
>         self.data.append(object)
> 
> using the 'data' instance variable automatically set up in the UserList
> class.

While this is a particular solution that works with the implementation
exposed by UserList, it's not a general answer to subclassing and
overriding in general.  For that, the right approach is to have your
subclass method call it's superclass when or if appropriate in any
overridden method.

> But I'll try the other suggestions anyway just to get a better
> understanding.

Think of this as exactly the same thing you are already doing in your
__init__ method (although you may just have copied that from other
examples).

When you subclass from UserList.UserList, you will inherit all of its
methods, such that when code tries to call a method in your instance
that doesn't exist, Python will walk the list of superclasses (only
UserList in this case) and try to call the method there.

But when you override a method - by defining it in your own class -
then Python calls that method on your own instance.  This is true in
your original example with your local definition of __init__.  So in
order to execute your superclass' __init__ code you have to call it
yourself.  In other languages this may happen automatically, whereas
in Python you have to be explicit about it, and in particular you
explicitly reference the superclass name (UserList.UserList in your
example) when making the call, so it's very clear that you're calling
your superclass.

But __init__ isn't special in this regard - this very same approach is
used for any method you may override.  And since you control when the
superclass function is called, you can perform pre or post processing
in your overridden method as appropriate, or even ignore completely
the original superclass method.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list