Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bestow string-ness on my class?

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?

like image 385
Tobias Avatar asked May 04 '09 16:05

Tobias


3 Answers

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
like image 154
Luper Rouch Avatar answered Sep 28 '22 17:09

Luper Rouch


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.

like image 25
Alex Martelli Avatar answered Sep 28 '22 15:09

Alex Martelli


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?

like image 36
Andrew Hare Avatar answered Sep 28 '22 15:09

Andrew Hare