__init__(self, *args, **kwargs) - why not always?

Jim Jewett JimJJewett at yahoo.com
Tue Jan 20 14:10:54 EST 2004


I'm still not sure I understand the objection, as I would
still have wanted the extension even in your examples. 

So I've gone into a bit more detail, and generalized the
replacement.


Is there any reason not to replace replace:

    class SubClass(BaseClass):
        def __init__(self, [what you used to take]):
            BaseClass.__init__(self, [what you used to send])

with:

    class SubClass(BaseClass):
        def __init__(self, [what you used to take], *args, **kwargs):
            BaseClass.__init__(self, [what you used to send], *args, **kwargs)

on a near-global basis?

Gerrit Holl <gerrit at nl.linux.org> wrote in message 
news:<mailman.521.1074550438.12720.python-list at python.org>...
 
> A subclass may be a specialized case, e.g.:
 
> class Tree:
>     def __init__(self, evergreen=False):
>         ...
 
> class Spruce(Tree):
>     def __init__(self):
>         Tree.__init__(self, True)

I do understand that you will sometimes need to
modify the argument (or keywords) based on your
subclass' needs.  My question is about unexpected
input -- which you might get if the base class is
later enhanced. What is wrong with the following:

    class Spruce(Tree):
        "Spruce are evergreen."
        def __init__(self, *args, **kwargs)
            eg = kwargs.pop('evergreen', True)
            Tree.__init__(self, eg, *args, **kwargs)

or 

    class Spruce(Tree):
        "Spruce are always evergreen, you annoying user!"
        def __init__(self, *args, **kwargs)
            kwargs['evergreen'] = True
            Tree.__init__(self, *args, **kwargs)


These will work even if tree is later enhanced to keep
track of which trees need extra attention.

    class Tree:
        def __init__(self, evergreen=False, healthy=True):
            ...


 
> or the other way around, e.g.

> class Enemy:
>     def __init__(self, pos):
>         ...
 
> class ShootingEnemy(Enemy):
>     def __init__(self, pos, bullets):
>         Enemy.__init__(pos)
>         ...

> In both cases I don't want to BaseClass.__init(self, *args, **kwargs)...

    class ShootingEnemy(Enemy):
        def __init__(self, pos, bullets, *args, **kwargs):
            Enemy.__init__(self, pos, *args, **kwargs)

indicates that the base class also needed to see position.
This wouldn't take any special thought that wasn't already 
required by passing position in your original example.

And again, it would remove some fragility in case the Enemy
class is later extended to indicate which army it is from,
or what type of unit.

-- 

-jJ  Take only memories.  Leave not even footprints.



More information about the Python-list mailing list