trouble subclassing str
Paul McGuire
ptmcg at austin.rr.com
Thu Jun 23 15:25:58 EDT 2005
My first thought is "make sure that subclassing str is really what you
want to do." Here is a place where I have a subclass of str that
really is a special kind of str:
class PaddedStr(str):
def __new__(cls,s,l,padc=' '):
if l > len(s):
s2 = "%s%s" % (s,padc*(l-len(s)))
return str.__new__(str,s2)
else:
return str.__new__(str,s)
print ">%s<" % PaddedStr("aaa",10)
print ">%s<" % PaddedStr("aaa",8,".")
(When subclassing str, you have to call str.__new__ from your
subclass's __new__ method, since str's are immutable. Don't forget
that __new__ requires a first parameter which is the input class. I
think the rest of my example is pretty self-explanatory.)
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.
-- Paul
More information about the Python-list
mailing list