How do I extend a class that I never instantiate myself?

Laura Creighton lac at openend.se
Sat Oct 10 15:09:51 EDT 2015


In a message of Sat, 10 Oct 2015 10:02:24 -0700, speeze.pearson at gmail.com write
s:

>I should just use the existing library's `Node` class, and write
>my library in a functional style. Don't define `MyNode.foo()`,
>instead define `mylibrary.foo(my_node)`.
>I've got nothing against functional programming, but mixing it
>so closely with OO would, I think, result in a confusing,
>schizophrenic interface.

This is one useful place to do some thinking.

Object-oriented programming is best used when you have a fixed set of
operations on things, and as you write more code, you mostly add
new things. Do this by adding new classes which implement existing
methods, and leave the existing classes alone.

Functional programming is best used when you have a fixed set of things,
and as you write more code, you mostly add new operations on
existing things. Do this by adding new functions that use the
existing data types, and leave the existing functions alone.

So do you have a horrible mismatch between the style of coding you
are doing and the job you expect to do?  If so, one possible way out
not discussed is to use multiple inheritance, and write a mixin class.  
What you say you want to do -- glue some extra methods onto an existing
class, or better yet a few extra classes -- is the classic use case 
for 'time to write a mixin'.

OO purists dislike mixin classes.  There is namespace pollution to 
worry about -- which is a real problem if you just multiply inherit
two independent classes both of which have authors who  are writing
code like crazy, but isn't so much if you are writing the mixin, and
worry about such things as they happen. 

Poor old Michele Simionato used Zope/Plone a lot and got bit a whole
lot by mixins, and wrote this:
http://www.artima.com/weblogs/viewpost.jsp?thread=246341 which I
include mostly for the very nice 'detect conflicts' decorator which I
use.  (Thank you Michele).  But while he thinks (or at least thought
when he wrote that) that Mixins are harmful, I think that the sort of
hell he found can be easily surpassed by misuse of decorators, and
the real rule is -- "People who write bad code make messes." which is hardly
original (or comforting).  A related problem is that lots of people
cannot do the thought you already did on this issue -- but everybody
can use multiple inheritance.  So lots of people who are new enough at
this business to have done practically no thought at all use 
multiple inheritance, badly.

All I am really saying -- I should condense this whole post but dinner
is about to arrive on the table -- is don't fear mixins and multiple
inheritance unduly.  They are a practical solution for a lot of
problems.  You might have one of them.

Laura






More information about the Python-list mailing list