开发者

python: overriding access a var

开发者 https://www.devze.com 2023-01-08 15:53 出处:网络
I have a class: class A: s = \'some string\' 开发者_JAVA技巧b = <SOME OTHER INSTANCE> now I want this class to have the functionality of a string whenever it can. That is:

I have a class:

class A:
    s = 'some string'
    开发者_JAVA技巧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?


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'


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)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消