Subclassing builtin types

Steve Holden sholden at holdenweb.com
Mon Mar 5 01:05:50 EST 2001


"Daniel Klein" <danielk at aracnet.com> wrote in message
news:ia15at4undkk6lpv7kn8l2nl9s3bgt30ln at 4ax.com...
> On Sun, 4 Mar 2001 12:41:55 -0500, "Steve Holden" <sholden at holdenweb.com>
> wrote:
>
> >> 1) Are wrapper classes for the builtin types a feasible (and pythonic)
> >thing to
> >> do?
> >>
> >Yes and yes: so feasible the library includes a UserList class which
> >provides esxactly what you seem to want: it wraps a list inside a class
so
> >you can inherit from it!
>
> Thanks Steve, you have just saved me a ton of work, something Python has a
> habit of doing consistently. :-)
>
Yes. Problem for me used to be doing some of the owrk before finding out
about the library module concerned. THe longer I use Python the less of a
problem this becomes, however.

> > Delegation is also a useful trick.
>
> I'm not sure what you mean by this. Are there any simple examples I can
look
> at?
>
> Dan

Well, there's the ftpStream mosule to which I referred in my last post. The
idea behind delegation is to create an instance of some other object,
storing it as an instance variable. Then you implement a __getattr__()
method which, when your object is asked for a non-existent method or
attribute attempts to return a reference to that method or attribute of the
saved instance object.

In ftpStream it works like this:

class ftpStream:
    "Specialised FTP with file-like interface."

    def __init__(self, host='', name='', passwd='', acct=''):
        "Create FTP object and set stream socket inactive."
        self.ftp = ftplib.FTP(host, name, passwd, acct)
        self.strsock = None

    def __getattr__(self, attrname):
        "Delegate unrecognised methods/attributes to the FTP object."
        return getattr(self.ftp, attrname)

In this case, calling ftpStream.cwd(path) causes the underlying FTP object's
cwd method to be used (because ftpStream has not cwd() method of its own).

The advantage of this is in avoiding naming conflicts: ftpStream has its own
close method, but it can easily call the close() method of its FTP object.

regards
 Steve






More information about the Python-list mailing list