Guy
Guy

Reputation: 14790

python: overriding access a var

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?

Upvotes: 0

Views: 167

Answers (3)

Rivka
Rivka

Reputation: 843

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)

Upvotes: 1

David Webb
David Webb

Reputation: 193696

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'

Upvotes: 7

Mad Scientist
Mad Scientist

Reputation: 18553

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

Upvotes: 1

Related Questions