字符串的ABC吗? [英] ABC for String?

查看:204
本文介绍了字符串的ABC吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在集合中发现了抽象基类(ABC),并且喜欢它们清晰,系统的方法和Mixins。现在,我也想创建海关字符串(*),但找不到字符串的ABC。

I recently discovered abstract base classes (ABCs) in collections and like their clear, systematic approach and Mixins. Now I also want to create customs strings (*), but I couldn't find an ABC for strings.

有UserString,但是不鼓励UserDict!从str本身派生出来就不会有Mixins吗?您如何在覆盖的方法中访问字符串的数据部分?

There is UserString, but UserDict was discouraged!? Deriving from str itself would have no Mixins? How would you access the "data" part of the string in overridden methods?

在某个地方,我看到了从Sequence和Hashable派生的建议,但是后来我写不出来如果在my_string中进行测试:?!

Somewhere I saw the suggestions to derive from Sequence and Hashable, but then I couldn't write if 'test' in my_string:?!

您推荐哪种方法?

(*)原因是:
-以内部定义的方式编写按顺序排列的字符串
-生成字符串(作为枚举的一部分),与枚举范围之外的值

(*) The reasons are: - write strings that order in an internally defined way - make string (as part of an enumeration), that throw errors when comparing to values outside the enumeration scope

推荐答案

这是史蒂文答案的一个愚蠢但快速的示例。它是在Python 3中实现的(即Unicode字符串,不带参数的 super __ getitem __ 切片):

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'

这篇关于字符串的ABC吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆