[Tutor] subclassing strings
eric at abrahamsen.com
Wed Jan 9 05:26:54 CET 2008
Thanks both of you, that cleared a lot of things up.
On Jan 9, 2008, at 11:49 AM, Kent Johnson wrote:
> No, you can't access the actual byte array from Python and you can't
> damage it.
I don't know a lick of C and probably never will, but I do like to
know what it is, exactly, that I don't know, and this is nice. I'll
stop worrying about stepping on the actual value of the strings.
On Jan 9, 2008, at 11:48 AM, Tiger12506 wrote:
> def __str__(self):
> return self
> def __repr__(self):
> return "'%s'" % self #Notice this will give extra single quotes
> around string
Excellent, this was very helpful. I know about the str() vs .__str__()
equivalence, but had never seen what these two functions were actually
doing under the hood.
What I wasn't figuring out was passing the string value of my custom
string class into the constructor of the actual str type, rather than
rerouting it into a data attribute of my custom class. So now I've got
this, for example:
def __init__(self, val):
self.timestamp = datetime.datetime.now()
so that this:
x = StampedString('This is a time-stamped string')
works exactly like a string, apart from the metadata.
At least, I think I've understood this correctly...
Thanks again for the interesting explanations.
More information about the Tutor