Type subclassing: bug or feature

Gerhard Häring gh_pythonlist at gmx.de
Thu Jun 13 22:09:24 EDT 2002


* Aahz <aahz at pythoncraft.com> [2002-06-13 16:08 -0400]:
> 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?

I once had the same problem with subclassing the list type/class: you'd
need to override every single method of the base class to make
subclassing of builtin Python types really useful. I ended up just
implementing the parts of the sequence protocol that I needed in the
particular case.

I'll look at the other answers if there is some clever soluiton using
__getattr__ or a metaclass. One day I'll have to figure out that
metaclass stuff, anyways. I still have no idea what it's all about.

Gerhard
-- 
This sig powered by Python!
Außentemperatur in München: 17.1 °C      Wind: 1.2 m/s





More information about the Python-list mailing list