Type subclassing: bug or feature
holger krekel
pyth at devel.trillke.net
Thu Jun 13 17:28:11 EDT 2002
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()
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
More information about the Python-list
mailing list