Question

Try to get a class which would work like so:

>>> original = u"ABCD-123-foo"
>>> suffix = SuffixComparingUnicodeString("foo")
>>> suffix == original    # if original ends with suffix, True
True

I know it's silly. Please bear with me.

Anyway, I can't figure out how to get the actual, er, string (not str, mind) from within the unicode object. I can do it like this just fine:

>>> class SuffixComparingUnicodeString(unicode):
...     def __init__(self, x):
...          super(SuffixComparingUnicodeString, self).__init__(x)
...          self._myval = x
...     def __eq__(self, other):
...          return isinstance(other, unicode) and other.endswith(self._myval)
...
>>> SuffixComparingUnicodeString("foo") == u"barfoo"
True

How can I do it without storing that value myself? What does unicode call its underlying character sequence?

Était-ce utile?

La solution

Since you a subclassing unicode, instances of SufficComparingUnicodeString can usually be used just like any other Unicode string. So you can just use other.endswith(self) in your __eq__() implementation:

class SuffixComparingUnicodeString(unicode):
    def __eq__(self, other):
        return isinstance(other, unicode) and other.endswith(self)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top