[Tutor] Poorly understood error involving class inheritance

Kent Johnson kent37 at tds.net
Thu Sep 10 23:17:05 CEST 2009


On Thu, Sep 10, 2009 at 4:51 PM, David Perlman <dperlman at wisc.edu> wrote:
> Well, here's what I am really doing:
>
> class oneStim(str):
>    def __init__(self, time, mods=[], dur=None, format='%1.2f'):
>        self.time=time
>        self.mods=mods
>        self.dur=dur
>        self.format=format

This is a bit odd because you don't call str.__init__() so you never
initialize the "str" part of a oneStim.

Actually when you subclass immutable, built-in classes you have to
override __new__() rather than __init__(). Here is an example:
http://mail.python.org/pipermail/python-list/2004-June/265368.html

> The purpose of this is to make an object that holds a collection of numbers
> and represents them as a specifically formatted string.  I want to be able
> to do something like:
>
>>>> z=oneStim(22.5678)
>>>> z.dur=10
>>>> z
> 22.57:10.00
>>>> len(z)
> 11
>>>> z.rjust(20)
> '             22.5678'
>
> Note that that doesn't work either.

You are expecting that str.rjust() accesses the string using
__repr__() but it doesn't, it directly accesses the internal data.

> It works fine like this, though:
>>>> z
> 22.57:10.00
>>>> str(z).rjust(20)
> '         22.57:10.00'
>
> I can work with that just fine, but I am curious to understand what's going
> on under the hood that makes it fail when subclassed from str...

I would skip the cleverness of trying to subclass string. You can use
str(z).rjust(20) as above, or use string formatting:
  '%20s' % z

Kent


More information about the Tutor mailing list