ABC for String?

狂风中的少年 提交于 2019-12-05 12:25:52

Here's a silly, but quick, example of Steven's answer. It's implemented in Python 3 (i.e. Unicode strings, super without arguments, and __getitem__ slices):

class MultiStr(str):
    def __new__(cls, string, multiplier=1, **kwds):
        self = super().__new__(cls, string, **kwds)
        self.multiplier = multiplier
        return self

    def __getitem__(self, index):
        item = super().__getitem__(index)
        return item * self.multiplier

>>> s = MultiStr(b'spam', multiplier=3, encoding='ascii')
>>> s[0]
'sss'
>>> s[:2]
'spspsp'
>>> s[:]
'spamspamspam'

You can just subclass str, you wouldn't need any mixins because you inherit everything you need from str itself. As for the "data" part: as you're not "simulating" a string (which is what you'd use UserString for), there is no need for a separate "data" part, use the string itself (that is: use self as you would use a string).

(if you mean something else: maybe the question would be clearer by showing your (attempted) code for the overridden methods)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!