__init__ concerns

David Bolen db3l at fitlinxx.com
Tue Dec 11 01:07:34 EST 2001


pzw1 at hotmail.com (Peter Wang) writes:

> however, the bigger question of properly calling parent classes'
> constructors still remains.  i figured you can always put a line into
> the subclass's constructor:
> 
> def __init__(self, *args):
>     apply(BASECLASS.__init__, (self,) + args)
> 
> but i thought this was kind of a kludge.  what is the proper python
> idiom (or, failing that, the proper technique) for ensuring that a
> subclass instance is properly initialized, especially when details of
> the base class are unknown?

As Erik points out, it's sort of unlikely that you would not know what
the constructor of one of your base classes needs.

However, yes, if you are just subclassing to add functionality and
need to override the constructor but are leaving the signature
completely alone and want to be as "pass-thru" as possible, the above
use of apply() is fairly common.  In fact, doing something like this
is useful enough that Python 2.0 added support for using *args and
**kwargs notation when making a function call in addition to declaring
a function.  So in Python 2.0+, the above could also be written as:

    def __init__(self, *args, **kwargs):
        BASECLASS.__init__(self,*args,**kwargs)

(dropping the kwargs part if you know there aren't any)

--
-- 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