0

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?

Guy
  • 14,178
  • 27
  • 67
  • 88
  • 2
    Is there a reason you _don't_ want to inherit from `str`? That would be the right way to do this. – Katriel Jul 26 '10 at 08:41
  • well, as the title of the question says, it's a more general question. This solution is good but I think overriding "access a var" will come in handy. – Guy Jul 26 '10 at 10:05

3 Answers3

7

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'
David Webb
  • 190,537
  • 57
  • 313
  • 299
1

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

Mad Scientist
  • 18,090
  • 12
  • 83
  • 109
  • Then use Dave's solution, that should support the whole string functionality. My solution only works for a small subset. – Mad Scientist Jul 26 '10 at 08:12
1

I found an answer in 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)
Community
  • 1
  • 1
Rivka
  • 823
  • 2
  • 7
  • 20