trouble subclassing str
Donn Cave
donn at u.washington.edu
Thu Jun 23 20:27:49 EDT 2005
In article <pan.2005.06.23.23.28.50.577481 at REMOVETHIScyber.com.au>,
Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:
> On Thu, 23 Jun 2005 12:25:58 -0700, Paul McGuire wrote:
>
> > But if you are subclassing str just so that you can easily print your
> > objects, look at implementing the __str__ instance method on your
> > class. Reserve inheritance for true "is-a" relationships. Often,
> > inheritance is misapplied when the designer really means "has-a" or
> > "is-implemented-using-a", and in these cases, the supposed superclass
> > is better referenced using a member variable, and delegating to it.
>
> Since we've just be talking about buzzwords in another thread, and the
> difficulty self-taught folks have in knowing what they are, I don't
> suppose somebody would like to give a simple, practical example of what
> Paul means?
>
> I'm going to take a punt here and guess. Instead of creating a sub-class
> of str, Paul suggests you simply create a class:
>
> class MyClass:
> def __init__(self, value):
> # value is expected to be a string
> self.value = self.mangle(value)
> def mangle(self, s):
> # do work on s to make sure it looks the way you want it to look
> return "*** " + s + " ***"
> def __str__(self):
> return self.value
>
> (only with error checking etc for production code).
>
> Then you use it like this:
>
> py> myprintablestr = MyClass("Lovely Spam!")
> py> print myprintablestr
> *** Lovely Spam!!! ***
>
> Am I close?
That's how I read it, with "value" as the member variable
that you delegate to.
Left unexplained is ``true "is-a" relationships''. Sounds
like an implicit contradiction -- you can't implement
something that truly is something else. Without that, and
maybe a more nuanced replacement for "is-implemented-using-a",
I don't see how you could really be sure of the point.
Donn Cave, donn at u.washington.edu
More information about the Python-list
mailing list