繁体   English   中英

如何正确地继承str?

[英]How to correctly inherit from str?

我被迫使用的sqlobject版本需要在自定义字符串类型上使用magic __unicode__ ,我正在尝试继承表单字符串并满足该要求:

class Foo(str):
    extra_attribute = 42

    def __repr__(self):
        return repr(self)  # optional

    def __unicode__(self):
        return unicode(self)  # infinite recursion
        return super(Foo, self).__unicode__()  # str doesn't have __unicode__
        return unicode(str(self))  # an ugly hack, but works

最后一行是我能做的最好的,还是有更清洁的方式?

显然,在Python 2.x中转换类似unicode的对象的正确方法是这样的:

return unicode(x)

或者,更详细地说:

if hasattr(x, "__unicode__"):
    return x.__unicode__()
else:
    return unicode(x)

不幸的是,我必须使用的sqlobject版本不会这样做。

正确的方法是解码为Unicode。 self.decode(some_encoding)

字节字符串可以是任何编码。 如果您始终使用ASCII,那么将其用作您的编解码器:

return self.decode('ASCII')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM