Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ABC for String?

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.

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?

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

Which approach do you recommend?

(*) 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

like image 432
Gerenuk Avatar asked Aug 24 '11 08:08

Gerenuk


People also ask

Is ABC a string?

A string is called ABC-string if it doesn't contain any symbols except 'A', 'B' or 'C'.

What is the difference between string a ABC and string a new string ABC?

String str = "abc"; is a String literal,where as String str = new String("abc") is a String Object.

How many objects are created String s new string?

By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”); It creates two objects (in String pool and in heap) and one reference variable where the variable 's' will refer to the object in the heap.

How many string objects are created in Java?

The answer is: 2 String objects are created. str and str2 both refer to the same object.


1 Answers

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'
like image 137
Eryk Sun Avatar answered Sep 19 '22 19:09

Eryk Sun