Type subclassing: bug or feature
Gustavo Cordova
gcordova at hebmex.com
Thu Jun 13 17:18:15 EDT 2002
> >
> > Consider the following code:
> >
> > class MyStr(str):
> > def contains(self, value):
> > return self.find(value) >= 0
> >
> > s = MyStr("hello, world!")
> > s = s.capitalize()
> > if s.contains('Hello'):
> > print "Found it!"
> >
> > It fails with an AttributeError when it calls s.contains(), because
> > s.capitalize() returned a str instead of a MyStr. Anyone
> want to take a
> > whack at defending this as the correct behavior?
> > --
> > Aahz (aahz at pythoncraft.com) <*>
> > http://www.pythoncraft.com/
>
> Looks like a bug to me. How can self be something else then
> what it is?
> Should MySocket return a socket, thus stripping off any additional
> functionality added by my derived class?
>
> David LeBlanc
> Seattle, WA USA
>
Hmmm...
maybe all methods of builtin types should do:
return self.__class__(return_value)
when returning a new object (like str methods).
-gustavo
More information about the Python-list
mailing list