问题描述
我有一堂课:
class A:
s = 'some string'
b = <SOME OTHER INSTANCE>
现在,我希望此类在任何可能的时候都具有字符串的功能。 那是:
a = A()
print a.b
将打印b
的值。
但是我希望那些期望字符串(例如replace
)的函数起作用。
例如:
'aaaa'.replace('a', a)
实际去做:
'aaa'.replace('a', a.s)
我尝试覆盖__get__
但这是不正确的。
我看到可以通过继承str
来做到这一点,但是没有它,有没有办法?
1楼
如果希望您的类具有字符串的功能,则只需扩展内置的字符串类即可。
>>> class A(str):
... b = 'some other value'
...
>>> a = A('x')
>>> a
'x'
>>> a.b
'some other value'
>>> 'aaa'.replace('a',a)
'xxx'
2楼
覆盖__str__
或__unicode__
来设置对象的字符串表示形式( )。
3楼
我在找到了一个答案。
我使用了Dave的解决方案并扩展了str,然后添加了一个新功能:
def __new__(self,a,b):
s=a
return str.__new__(A,s)