views:

51

answers:

3

I have a class:

class A:
    s = 'some string'
    b = <SOME OTHER INSTANCE>

now I want this class to have the functionality of a string whenever it can. That is:

a = A()
print a.b

will print b's value. But I want functions that expect a string (for example replace) to work. For example:

'aaaa'.replace('a', a)

to actually do:

'aaa'.replace('a', a.s)

I tried overidding __get__ but this isn't correct.

I see that you can do this by subclassing str, but is there a way without it?

+1  A: 

Override __str__ or __unicode__ to set the string representation of an object (Python documentation).

Fabian
This doesn't help.
Rivka
Then use Dave's solution, that should support the whole string functionality. My solution only works for a small subset.
Fabian
+7  A: 

If you want your class to have the functionality of a string, just extend the built in string class.

>>> class A(str):
...     b = 'some other value'
...
>>> a = A('x')
>>> a
'x'
>>> a.b
'some other value'
>>> 'aaa'.replace('a',a)
'xxx'
Dave Webb
+1  A: 

I found an answer in http://stackoverflow.com/questions/1565374/subclassing-python-tuple-with-multiple-init-arguments .

I used Dave's solution and extended str, and then added a new function:

def __new__(self,a,b):
    s=a
    return str.__new__(A,s)
Rivka