[Tutor] designing a class

Terry Carroll carroll at tjc.com
Fri Jan 27 01:02:37 CET 2006

On Thu, 26 Jan 2006, Christopher Spears wrote:

> Here is an exercise out of Learning Python:

Which edition?  If I recall, the second edition covers through a release
of Python (2.2?) that permits direct subclassing of lists; while the
earlier one came out prior to Python 2.2, and would expect you to fake it
out a bit by subclassing USerList.
> Write a class called Mylist that shadows ("wraps") a
> Python list: 

Okay; what this means is that you're defining a class by subclassing the 
list type (or UserList type, for pre-2.2).

> it should overload most list operators
> and operations including...

This meens you need to write a bunch of methods name __x__ where "x" is 
some specific name that is related to the task listed in the problem.

You'll find most of these, I think, in section 3.3 of the reference
Manual; see http://docs.python.org/ref/specialnames.html and the pages
that follow.

For some examples,

> +, 

That would be __add__ ; see http://docs.python.org/ref/numeric-types.html

> indexing, iteration,
> slicing, and list methods such as append and sort.

Most of these are discussed at 
http://docs.python.org/ref/sequence-methods.html  There seem to be quite a 
lot of them!  I'm wondering if you can skip most of them; one advantage of 
subclassing is to be able to rely on the superclasses implementations.

> Also, provide a constructor for
> your class that takes an existing list (or a Mylist
> instance) and copies it components inro an instance
> member.

That's __init__.

> When I read this, I feel like a deer caught in the
> headlights.  Where should I begin?  How do I go about
> designing a new class?

I would suggest you first just successfully subclass the list builtin.  
(Even if you're using the First Edition of LP, I'd go with subclassing 
list directly, rather than using UserList.  If you're on a sufficiently 
old version of Python that you can't do that, enough has changed that it's 
worth upgrading.)

Play with that, adding and printing list members.

Once you have that down, add your __init__ to support initialization by 
making a copy.

Then add the other pieces.

Small steps, get some confidence, then work forwards.

More information about the Tutor mailing list