[
74
]
The previous example does what it is supposed to do. But it's starting to look messy,
and it has become difficult to answer the question,
What arguments do we need to pass
into
Friend.__init__
? This is the foremost question for anyone planning to use the
class, so a docstring should be added to the method to explain what is happening.
Further, even this
implementation is insufficient if we want to
reuse
variables in
parent classes. When we pass the
**kwargs
variable to
super
, the dictionary does
not include any of the variables that were included as explicit keyword arguments.
For example, in
Friend.__init__
, the call to
super
does not have
phone
in the
kwargs
dictionary. If any of the other classes need the
phone
parameter, we need
to ensure it is in the dictionary that is passed. Worse, if we forget to do this, it will
be tough to debug because the superclass will not complain, but will simply assign
the default value (in this case, an empty string) to the variable.
There are a few ways to ensure that the variable is passed upwards. Assume the
Contact
class does, for some reason, need to be initialized with a
phone
parameter,
and the
Friend
class will also need access to it. We can do any of the following:
•
Don't include
phone
as an explicit keyword argument. Instead, leave
it in the
kwargs
dictionary.
Friend
can look it up using the syntax
kwargs['phone']
. When it passes
**kwargs
to the
super
call,
phone
will still be in the dictionary.
•
Make
phone
an explicit keyword argument but update the
kwargs
dictionary before passing it to
super
, using the standard dictionary
syntax
kwargs['phone'] = phone
.
•
Make
phone
an explicit keyword argument, but update the
kwargs
dictionary using the
kwargs.update
method. This is useful if you have
several arguments to update. You can create the dictionary passed into
update
using either the
dict(phone=phone)
constructor, or the dictionary
syntax
{'phone': phone}
.
•
Make
phone
an explicit keyword argument, but pass it to the super call
explicitly with the syntax
super().__init__(phone=phone, **kwargs)
.
We have covered many of the caveats involved with multiple inheritance in Python.
When we need to account for all the possible situations, we have to plan for them
and our code will get messy. Basic multiple inheritance can be handy but, in many
cases, we may want to choose a more transparent way of combining two disparate
classes, usually using composition or one of the design patterns we'll be covering
in
Chapter 10
,
Python Design Patterns I
and
Chapter 11
,
Python Design Patterns II
.
www.it-ebooks.info
Chapter 3
Do'stlaringiz bilan baham: |