[Python-3000] State of the object system
Jim Jewett
jimjjewett at gmail.com
Fri May 26 19:53:22 CEST 2006
On 5/26/06, Michael Chermside <mcherm at mcherm.com> wrote:
> On 5/18/06, Kay Schluehr <kay.schluehr at gmx.net> wrote:
> > Adding a
> > method isprime() or iseven() to a subclass of int will suddenly be lost
> > in the resulting object after an operation as long as it is not
> > overwritten to return the right type and not the base type. So it is
> > questionable if subclassing is really a good design decision.
> That's why int subclasses can override both __add__ and __radd__
> to ensure that your subclass is returned when combined with normal
> ints. But I agree that it's not a good decision... making "isprime()" or
> "iseven()" a helper function (not method) is probably a better design.
With strings, you need to override __add__ and __radd__ (which objects
of the base class don't even have), and __mul__ and __rmul__. Good
luck overriding __str__.
Do also override non-magic methods capitalize, center, join, ljust,
lower, lstrip, replace, rjust, rsplit, rstrip, split, splitlines,
strip, swapcase, title, translate, upper, zfill, perhaps encode and
decode,
I do like Josiah's suggestion that if a method returns an instance of
its own type, it should instead return the derived type for types that
don't bother to override the method. There is a bit of a corner case
when a method takes multiple arguments (as join does), but I suppose
the resolution used for numbers works well enough.[1]
-jJ
[1] Assume type(self), but switch to a subclass if one of the other
arguments is strictly more specific.
class S1(str): pass
class S2(str): pass
str() + S1() -> S1
S1() + S2() -> S1, because S2 is not a subclass of S1
More information about the Python-3000
mailing list