[Tutor] subclassing strings
Eric Abrahamsen
eric at abrahamsen.com
Wed Jan 9 03:43:19 CET 2008
I'm playing around with subclassing the built-in string type, and
realizing there's quite a bit I don't know about what's going on with
the built-in types. When I create a string like so:
x = 'myvalue'
my understanding is that this is equivalent to:
x = str('myvalue')
and that this second form is more fundamental: the first is a
shorthand for the second. What is 'str()' exactly? Is it a class name?
If so, is the string value I pass in assigned to an attribute, the way
I might create a "self.value =" statement in the __init__ function of
a class I made myself? If so, does that interior attribute have a
name? I've gone poking in the python lib, but haven't found anything
enlightening.
I started out wanting to subclass str so I could add metadata to
objects which would otherwise behave exactly like strings. But then I
started wondering where the actual value of the string was stored,
since I wasn't doing it myself, and whether I'd need to be careful of
__repr__ and __str__ so as not to interfere with the basic string
functioning of the object. As far as I can tell the object functions
normally as a string without my doing anything – where does the string
value 'go', and is there any way I might inadvertently step on it by
overriding the wrong attribute or method?
Thanks for any insight,
Eric
More information about the Tutor
mailing list