使用自定义python对象模拟字符串

时间:2013-11-07 11:12:02

标签: python string lazy-evaluation

我想以下面的测试代码应该工作的方式模拟带有自定义python对象的字符串:

import os
class A(str):
    path=""

    def __repr__(self):
        return self.path
    def __str__(self):
        return self.path

a=A()
a.path = "myfile"

print os.path.join('mydir',a)

我在期待

mydir/myfile

但我只有

mydir/

如何编写我的类来模拟字符串?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用UserString.UserString而不是直接继承字符串:

import os
from UserString import UserString

class A(UserString):

    def __init__(self, initial=''):
        self.data = initial

    @property
    def path(self):
        return self.data

    @path.setter
    def path(self, value):
        self.data = value

a=A()
a.path = "myfile"

print(os.path.join('mydir',a))

编辑:我使用python3' s collection.UserString编写了答案,然后发现它也被反向移植到python2。