Where does str class represent its data?

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Wed Jul 11 23:20:56 EDT 2007


On Jul 11, 4:21 pm, ChrisEdge... at gmail.com wrote:
> I'd like to implement a subclass of string that works like this:
>
> >>>m = MyString('mail')
> >>>m == 'fail'
> True
> >>>m == 'mail'
> False
> >>>m in ['fail', hail']
>
> True
>
> My best attempt for something like this is:
>
> class MyString(str):
>   def __init__(self, seq):
>     if self == self.clean(seq): pass
>     else: self = MyString(self.clean(seq))
>
>   def clean(self, seq):
>     seq = seq.replace("m", "f")
>
> but this doesn't work.  Nothing gets changed.
>


What about subclassing str and redefining __eq__:

>>> class MyString(str):
...     def __eq__(self, other):
...         return not str.__eq__(self, other)
...
>>> m = MyString('mail')
>>> m == 'fail'
True
>>> m == 'mail'
False
>>> m in ['fail', 'hail']
True


--
Hope this helps,
Steven






More information about the Python-list mailing list