python:重写访问

2024-04-27 02:44:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一门课:

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来实现这一点,但是有没有办法不使用它呢?你知道吗


Tags: instance函数字符串功能getstringsomereplace
3条回答

重写__str____unicode__以设置对象的字符串表示形式(Python documentation)。你知道吗

如果希望类具有字符串的功能,只需扩展内置的字符串类。你知道吗

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

我在Subclassing Python tuple with multiple __init__ arguments中找到了答案。你知道吗

我使用了Dave的解决方案和扩展str,然后添加了一个新的函数:

def __new__(self,a,b):
    s=a
    return str.__new__(A,s)

相关问题 更多 >