Multiple inheritance, super() and changing signature
Ben Finney
ben+python at benfinney.id.au
Fri Jun 3 16:16:27 EDT 2016
Nagy László Zsolt <gandalf at shopzeus.com> writes:
> So you are right: the custom __init__ in the BootstrapDesktop class is
> not really needed, and does not do anything useful in that particular
> class.
I disagree: setting initial attributes is a normal and useful case for
defining a custom initialiser.
> My original statement was this: "I have to initialize some default
> attributes", and for that I need to pass arguments.
Yes. If you need to initialise the instance, that's what a custom
‘__init__’ is for.
> The truthness of this statement is not affected by adding a useless
> override of a method (with the very same parameters). Even though I
> see that you are right in what you wrote, I think I don't understand
> the point because it seem unrelated.
My point was rather that if the custom initialiser does *nothing* except
call the superclass's initialiser, then there's no purpose to writing
the custom initialiser.
If you're writing a custom initialiser that handles two additional
parameters, then those parameters should not be present when you call
the super() method's initialiser::
# You specified Python 3, which allows simpler syntax.
class LoremIpsum:
def __init__(self, spam, *args, **kwargs):
do_something_important_with(spam)
super().__init__(*args, **kwargs)
class DolorSitAmet(LoremIpsum):
def __init__(self, spam, eggs=4, beans=None, *args, **kwargs):
self.eggs = eggs
self.beans = beans
super().__init__(spam, *args, **kwargs)
So the sub-class follows the Liskov Substitution Principle: every
DolorSitAmet instance should be substitutable for LoremIpsum instances,
and users that only expect a LoremIpsum instance should not need to know
any difference.
This entails that its methods (in this case the initialiser) will accept
the same parameters as ‘LoremIpsum.__init__’, and do the same things
with those parameters. We make that explicit by omitting the
*additional* parameters that we already handled, ‘eggs’ and ‘beans’,
from the next call in the chain.
--
\ “The difference between religions and cults is determined by |
`\ how much real estate is owned.” —Frank Zappa |
_o__) |
Ben Finney
More information about the Python-list
mailing list