python:重写访问var

Guy*_*Guy 0 python overriding

我有一节课:

class A:
    s = 'some string'
    b = <SOME OTHER INSTANCE>
Run Code Online (Sandbox Code Playgroud)

现在我希望这个类尽可能具有字符串的功能.那是:

a = A()
print a.b
Run Code Online (Sandbox Code Playgroud)

将印刷b的价值.但是我想要希望字符串(例如replace)工作的函数.例如:

'aaaa'.replace('a', a)
Run Code Online (Sandbox Code Playgroud)

实际上:

'aaa'.replace('a', a.s)
Run Code Online (Sandbox Code Playgroud)

我试过覆盖,__get__但这不正确.

我看到你可以通过子类化来做到这一点str,但有没有它没有它?

Dav*_*ebb 7

如果您希望您的类具有字符串的功能,只需扩展内置的字符串类.

>>> class A(str):
...     b = 'some other value'
...
>>> a = A('x')
>>> a
'x'
>>> a.b
'some other value'
>>> 'aaa'.replace('a',a)
'xxx'
Run Code Online (Sandbox Code Playgroud)