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
def __cmp__(self,other):
return cmp(self.time,other.time)
def __repr__(self):
timestr=self.format % self.time
if self.mods == []:
modstr=''
else:
modstr = '*' + ','.join(self.format % i for i in self.mods)
if self.dur == None:
durstr = ''
else:
durstr = ':' + (self.format % self.dur)
return timestr + modstr + durstr
def __len__(self):
return len(self.__repr__())
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. 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...
On Sep 10, 2009, at 3:42 PM, Serdar Tumgoren wrote:
class dummy2(str):
... def __init__(self,dur=0):
... self.dur=dur
...
z=dummy2(3)
z.dur
3
So far so good. But:
z=dummy2(dur=3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dur' is an invalid keyword argument for this function
I think you're problem may stem from the fact that you subclassed the
string type and then tried to pass in an integer.
class Dummy2(int):
... def __init__(self, dur=0):
... self.dur = dur
...
z = Dummy2(3)
z.dur
3
When you sub "int" for "str", it seems to work. Is there a reason
you're not just subclassing "object"? I believe doing so would give
you the best of both worlds.
--
-dave----------------------------------------------------------------
"Pseudo-colored pictures of a person's brain lighting up are
undoubtedly more persuasive than a pattern of squiggles produced by a
polygraph. That could be a big problem if the goal is to get to the
truth." -Dr. Steven Hyman, Harvard
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor