views:

187

answers:

4

I want a string with one additional attribute, let's say whether to print it in red or green.

Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying.

Can multiple inheritence help? I never used that.

Inheriting only object and using self.value=str means I have to implement all string-ness messages (like strip) myself.

Or is there a way to forward them, like Ruby's missing_method?

I think using a class-level dictionary indexed by instance to store the color could work. Too ugly?

+2  A: 

Perhaps a custom class that contains a string would be a better approach. Do you really need to pass all string methods through to the underlying string? Why not expose the string via a property and allow consumers of the class to do whatever they wish to it?

Andrew Hare
A: 

You need all of string's methods, so extend string and add your extra details. So what if string is immutable? Just make your class immutable, too. Then you're creating new objects anyway so you won't accidentally mess up thinking that it's a mutable object.

Or, if Python has one, extend a mutable variant of string. I'm not familiar enough with Python to know if such a structure exists.

Welbog
+2  A: 

str can be inherited unless you are using a very old python version, for example :

>>> class A(str):
...    def __new__(cls, color, *args, **kwargs):
...        newobj = str.__new__(cls, *args, **kwargs)
...        newobj.color = color
...        return newobj
>>> a = A("#fff", "horse")
>>> a.color
'#fff'
>>> a
'horse'
>>> a.startswith("h")
True
Luper Rouch
This is good. But you need to be careful with this approach. If you made any string operation like (title(), +, ...) the result will be of type str not A.
Nadia Alramli
I was under the impression that precisely this would NOT work, hence the question. Turns out it was a pogramming error in my __new__ and I misinterpreted Python's inadequate message.
Tobias
+2  A: 
import UserString
class mystr(UserString.MutableString):
   ...

It's generally best to use immutable strings & subclasses thereof, but if you need a mutable one this is the simplest way to get it.

Alex Martelli
This is deprecated since python 2.2
Luper Rouch
The UserString class was deprecated in 2.2, but the MutableString class was only deprecated in 2.6 -- see http://docs.python.org/library/userdict.html -- if you're sure you're going to be using 2.6 or later, a mutable string can be implemented on top of the new bytearray type (mutable array of bytes)
Alex Martelli