Type subclassing: bug or feature
holger krekel
pyth at devel.trillke.net
Thu Jun 13 17:50:28 EDT 2002
To Aahz wrote:
> Aahz wrote:
> > 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?
>
> class Names(str):
> def __init__(self, namelist):
> str.__init__(self, ":".join(namelist))
>
> what would you expect
>
> Names([1,2,3]).capitalize()
oops. sorry. should have checked it better (or at all<self.wink>)...
class Names(str):
def __new__(cls, namelist):
return str.__new__(str, ":".join(namelist))
n=Names(['tim','peter','guido'])
But hopefully my point was understandable that it is hard
to guess a return type for 'n.capitalize()' now ...
> to return? An exception? I think it's dangerous to assume anything
> about the subtyped classes' constructor. You *do* need a constructor
> because strings are immutable so 'str.capitalize' can't modify
> anything in place.
>
> if-you-subtype-cake-you-gotta-eat-it-all-ly y'rs, holger
cheers,
holger
More information about the Python-list
mailing list