Inheritance and name clashes

Steve Howell showell30 at yahoo.com
Sun Oct 3 17:47:18 EDT 2010


On Oct 3, 1:07 pm, Rock <rocco.ro... at gmail.com> wrote:
> Hi all :)
>
> I've really been wondering about the following lately. The question is
> this: if there are no (real) private or protected members in Python,
> how can you be sure, when inheriting from another class, that you
> won't wind up overriding, and possibly clobbering some important data
> field of the parent class, which might compromise its entire
> functionality?
>
> I mean, nevermind the double underscore business, I know all about it.
> But, honestly, not everybody uses that, so you can't really be sure
> about what you're doing, right? Maybe the author forgot to warn about
> some special member in the docs for instance, or even worse, it's a
> third-party library, perhaps with no source! So how can you be sure???
> The way I see it ... you can't!
>
> Am I wrong?
>
> Please give me a hand on this one :)
>

The nice thing about Python (and other duck-typed languages) is that
it doesn't force you to use inheritance when you simply want two
classes to have the same API.  If you have two classes with similar
APIs but different internal implementations, just code separate
classes.

Inheritance can be useful when you want class B to leverage the
internal details of class A.  Obviously, if you choose this strategy,
you need to have control over the internal implementation of class A.

If you are designing a class that you intend to be extended through
inheritance, one way to prevent naive subclasses from poking into your
internals is to create useful APIs within the superclass to change the
behavior.  But instead of focusing on making inheritance work at any
cost, the pitfalls of inheritance can often point you to better
designs.  If your class needs to be subclassed in many different ways
to be useful, it's possible that it's not carrying its own weight, and
you just need to be the superclass more flexible.  Or you can have
quite the opposite problem--you have two classes in an inheritance
structure that are trying to do too much, when a simpler design might
have three or four non-coupled classes that each do one job well.

Object-oriented designs are difficult to design in any programming
language, and it helps to have some sort of concrete problem to drive
the discussion.  Are you working on a particular design where you
think Python's philosophy will inhibit good design?  My take on Python
is that it focuses more on enabling good designs than preventing bad
designs.  I prefer this to Java, for example, which I feel inhibits me
from expressiveness at a higher cost than any supposed benefits
private/protected would give me.





More information about the Python-list mailing list