Type subclassing: bug or feature
Bengt Richter
bokr at oz.net
Thu Jun 13 16:44:35 EDT 2002
On 13 Jun 2002 16:08:40 -0400, aahz at pythoncraft.com (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?
I don't think you could generally coerce base class method results
to subclass instances, so I think it has to be explicit. Maybe it
could be done with a method list for a more compact way (using a metaclass?)
Anyway:
>>> class MyStr(str):
... def contains(self, value):
... return self.find(value) >= 0
... def capitalize(self):
... return MyStr(str.capitalize(self))
...
>>> s = MyStr("hello, world!")
>>> s = s.capitalize()
>>> if s.contains('Hello'):
... print "Found it!"
...
Found it!
Regards,
Bengt Richter
More information about the Python-list
mailing list