trouble subclassing str

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Jun 23 19:28:51 EDT 2005


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?


-- 
Steven




More information about the Python-list mailing list