subclassing str

Mark Wooding mdw at distorted.org.uk
Tue Nov 9 22:36:52 CET 2010


rantingrick <rantingrick at gmail.com> writes:

> One thing i love about Python is the fact that it can please almost
> all the "religious paradigm zealots" with it's multiple choice
> approach to programming. However some of the features that OOP
> fundamentalists hold dear in their heart are not always achievable in
> a clean manner with Python. Yes you could use a function but that is
> not the OOP way.

It can be more than just an aesthetic difference.  Sometimes it can be
nice to extend existing classes to understand additional protocols.  For
example, suppose you're implementing some object serialization format:
it'd be really nice if you could add `serialize' methods to `str',
`int', `list' and friends.  This is certainly the Smalltalk way.
Unfortunately, you can't do it in Python.

One option is to implement a subclass which implements the additional
protocol.  This causes fragmentation: now each protocol wants its own
subclass: if you want an object which understands both protocols, you
need to mess with multiple inheritance[1] (and, in Python, at least,
hope that everyone is using `super' properly to implement upwards
delegation).

Otherwise you have to do the dispatch yourself, either by hand or by
using one of the generic function/multimethod frameworks.

[1] At least Python gives you a fighting chance of getting this to work.
    Java and C# won't countenance multiple inheritance at all, and C++
    will botch it all by giving you a separate copy of the common
    superclass's state for each protocol implementation (what are the
    chances that everyone decided to use a virtual base class?) /and/
    hideously breaking upwards delegation.

-- [mdw]



More information about the Python-list mailing list