Usefulness of subclassing builtin number types

holger krekel pyth at devel.trillke.net
Mon Dec 16 06:25:22 EST 2002


Lulu of the Lotus-Eaters wrote:
> |* Skip Montanaro <skip at pobox.com> [2002-12-15 17:01 -0600]:
> |>     class MyInt(int):
> |>         def __imul__(self, other):
> |>             return MyInt(self*other)
> 
> Gerhard =?iso-8859-1?Q?H=E4ring?= <gerhard.haering at gmx.de> wrote previously:
> |I want the objects of my class to keep being objects of my class for
> |all artithmetic operations.  At least as long as both operands are
> |MyInts.  My complaint was that I have to do this for almost all methods
> |of 'int'.  There's little gain here compared to just implementing the
> |number protocol.
> 
> It would be nice if someone, say Gerhard :), were to create a UserInt
> module that defined all those methods.  Much as with UserList, the next
> person customizing an int would not need to remember all the methods.
> Instead, we could just inherit from UserInt.UserInt, then customize only
> the few methods we were interested in.

that's another name, module and concept one would have to remember.  

Couldn't the builtin types's methods use 

    self.__class__(...)

to construct new objects?  I have seen this technique in some python
modules and ASFAIK they work nicely and allow plugging in your own extended
types. 

> But this effort is a one-time thing.  The pattern is straightforward,
> and it can easily put into a module.

you'd have to do it for dict, str, int, float, ...

    holger




More information about the Python-list mailing list