1

给定这堂课

class Stringy(unicode):
    def __init__(self,something):
        self.something = something
    def __repr__(self):
        return "Stringy(%s)"%repr(self.something)
    def __str__(self):
        return "str(%s)"%repr(self.something)
    def __unicode__(self):
        return "unicode(%s)"%repr(self.something)

运行以下

s = Stringy("Hello")
print s.lower()  #prints "hello" !!! Why?
print s  # correctly prints str('Hello')
print unicode(s) #correctly prints unicode('Hello')
print [s]        #correctly prints Stringy('Hello')
print s.upper()  #prints "HELLO"  !!! Why?

为什么upper// loweretc 不触发__str__方法?

引擎盖下不应该 unicode(self).lower()发生类似的事情吗?

还是str(self).lower()

4

3 回答 3

2

s.lower正在调用unicode.lower(),所以你得到一个新的不同的 unicode 对象

您需要有lower()返回Stringy对象的方法

例如。

def lower(self):
    return Stringy(unicode.lower(self))
于 2012-12-17T21:53:56.517 回答
1

因为字符串是不可变的,调用upper()它会返回一个字符串。您的新字符串将是一个实际unicode实例,而不是Stringy.

于 2012-12-17T21:53:50.693 回答
0

print不会触发,Stringy.__str__()因为结果s.lower()是一个全新的类型对象unicode

In [3]: type(Stringy('').lower())
Out[3]: unicode
于 2012-12-17T21:53:50.113 回答