Where does str class represent its data?
Miles
semanticist at gmail.com
Wed Jul 11 19:37:05 EDT 2007
On Jul 11, 7: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.
>
> I understand that I could just remove the clean function from the
> class and call it every time, but I use this class in several
> locations, and I think it would be much safer to have it do the
> cleaning itself.
Since strings are immutable, you need to override the __new__ method.
See http://www.python.org/download/releases/2.2.3/descrintro/#__new__
More information about the Python-list
mailing list