python constructor overloading

dj trombley badzen at yifan.net
Fri Dec 17 02:36:10 EST 1999


Greg Copeland wrote:
> 
> Okay, I have two classed in a container object.  I'd like to be able to
> pass the container to both of the contained objects so that they can
> call some methods that exist in the container.  Both objects are derived
> from objects in another library.  So, I don't want to have to change the
> other objects (as that would be anti-OO and anti-reuse, IMOHO).  At any
> rate, my first thought was that I would overload the constructor of my
> newly derived objects.  The problem is, I'm not sure how to do this.  I
> looke in the FAQ, needless to say, those solutions suck.  As it stands,
> it doesn't really look like you can overload constructors.  The end
> result that I'm looking for is something like this:
> 
> # This is from another library
> class base
> 
> # This is mine
> class derived( base ):
>         def __init__( self, caller, arg1, arg2, arg3 ):
>                 self.caller = caller
>                 base.__init__( arg1, arg2, arg3 )
> 

That is perfectly valid - except for one error - you need to pass the
instance
as the first argument to the (unbound) constructor method.

For example:
base.__init__(self, arg1, arg2, arg3)

If you really do want to overload a constructor method, you may do so by
simply
assigning an appropriate initializer function to the class's __init__
attribute.

I am not sure exactly what you mean by a 'container class', but if you
don't already know,
Python supports multiple inheritence.

For example:
class foo(bar, baz):
   def __init__(self):
      bar.__init__(self, <args>)
      baz.__init__(self, <args>)

Hope this helps.

-dj

Dave Trombley
<badzen at yifan.net>



More information about the Python-list mailing list