Type subclassing: bug or feature

Anders J. Munch andersjm at dancontrol.dk
Mon Jun 17 13:14:06 CEST 2002

"Aahz" <aahz at pythoncraft.com> 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?

Inheriting from a class/type with value semantics is usually bad
design.  Use containment or helper functions instead.

but-that-doesn't-make-it-a-good-idea-ly y'rs, Anders

More information about the Python-list mailing list