ABC for String?

I recently discovered abstract base classes (ABC) in collections and how their clear, systematic approach and Mixins are. Now I also want to create custom strings (*), but I could not find ABC for strings.

There is a UserString, but a UserDict is not recommended !? The output from the line itself would not have Miksinov? How can you access a piece of data "data" in overridden methods?

Somewhere I saw sentences that can be obtained from Sequence and Hashable, but then I could not write if 'test' in my_string: ?!

Which approach do you recommend?

(*) Reasons: - write lines that are ordered internally in a specific way - create a line (as part of the enumeration) that produces errors when comparing with values ​​outside the enumeration area

+4
source share
2 answers

Here's a silly but quick example of Stephen. It is implemented in Python 3 (i.e. Unicode, super strings with no 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' 
+2
source

You can simply subclass str , you don’t need any mixins, because you inherit everything you need from str . As for the “data” part: since you are not “imitating” the string (this is what you would use a UserString for), there is no need for a separate “data” part, use the string itself (this is: use self , since you would use the string )

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

+1
source

All Articles