Python 为什么在调用 my_string.lower() 时不调用 str 或 repr 或 Unicode



给定这个类

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/lower/etc 不触发 __str__ 方法?

不应该在引擎盖下像这样的东西 unicode(self).lower()发生?

还是str(self).lower()

s.lower正在调用unicode.lower(),因此您将获得一个新的不同Unicode对象

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

例如。

def lower(self):
    return Stringy(unicode.lower(self))

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

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

In [3]: type(Stringy('').lower())
Out[3]: unicode

最新更新