0

我想创建一个类似字符串的对象,它可以定义一些基本str类型没有的额外方法。子类化str类型显然不是要走的路,所以我考虑过使用封装策略,但不知道如何使对象在传递给其他函数时像字符串一样open

class StringLike(object):

    def __init__(self, string):
        self.string = string

    def __str__(self, string):
        return self.string

s = StringLike('~/Desktop/test.txt')
with open(s, 'w') as handle: handle.write('Hello world')

#----------------------------------------------------------------------#
#TypeError: coercing to Unicode: need string or buffer, StringLike found
4

2 回答 2

0

你需要做

with open(s.string, 'w') as handle: handle.write('Hello world')

或者

with open(str(s), 'w') as handle: handle.write('Hello world')
于 2013-07-01T16:07:15.263 回答
0

您应该覆盖它__getattr____setattr__方法,如下所示:

这将充当普通字符串,除了它具有额外的方法 from_str,您可以根据需要添加更多额外的方法。

class Student(object):
    def __init__(self, name):
        # define your internal stuff here, with self.__dict__
        self.__dict__['name'] = name

    def __getattr__(self, attr):
        return self.name.__getattribute__(attr)

    def from_str(self, txt):
        self.name = txt

    def __setattr__(self, attr, value):
        if not attr in self.__dict__:
         return self.name.__setattr__(attr, value)
        else:
          self.__dict__[attr] = value


student = Student('test')
print student.upper()
>>>TEST
student.from_str('foo')
>>> print student.upper()
FOO
于 2014-01-29T15:31:16.877 回答