Another stylistic question: passing on arguments

James Kew james.kew at btinternet.com
Tue Sep 3 17:31:33 EDT 2002


I have a class hierarchy in which the __init__ method must always have the
same signature: the classes are all validators for various sorts of file,
and by having them all expose the same initialisation and checking methods I
can happily use them polymorphically. So far so good.

However, sometimes in derived classes I need to initialise additional
instance data at __init__ time. Up to now, I've happily overriden __init__
in derived classes, done my derived-class-specific stuff, and then delegated
down to the base class __init__.

Today, though, I wanted to add an extra argument to the __init__ method. The
extra argument is only meaningful to the base class. So, I merrily added it
to the base class __init__, blissfully forgot to modify the derived classes
__init__s, ran it up, and of course it blew up at runtime as now some
classes take three parameters on __init__ and some take two.

Alex posted this a while ago, which I tucked away in my Inbox and which
burrowed itself into my subconscious:
http://groups.google.co.uk/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=kNw%258.1
31213%24vm5.4318544%40news2.tin.it

particularly his advice that:
> In fact: when you wrap a library class, please CONSIDER accepting
> arbitrary keyword parameters and passing them up to the superclass's
> method that you're overriding-and-delegating-to.  Just in case this
> sort of thing happens tomorrow.  Pretty please.

My C/C++ background doesn't get me beyond varargs and default values as far
as variable argument lists go, but I'm starting to see now the power of the
positional and keyword argument * and ** syntax. I'm thinking that, had I
written my derived class __init__s to catch and pass on additional arguments
to the base class, my base-class-only change would have been transparent to
derived classes.

But is that just using a nifty Python tool because it's there? I suspect my
"same __init__ signature everywhere" requirement would be better met by
defining __init__ only in the base class and having it delegate out to an
empty do_init method which derived classes can override.


Um: I think I've just argued myself into the second solution. But I'll be
playing with the *args, **kwargs syntax to add it to my toolbox; and I
wanted to thank Alex for helping this newbie along the Python path.

--
James Kew
james.kew at btinternet.com





More information about the Python-list mailing list