Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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?

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.

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.

You could try using the stringlike module in PyPI. Here's an example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top