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?
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
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With