Usefulness of subclassing builtin number types
Gerhard Häring
gerhard.haering at gmx.de
Sun Dec 15 18:28:28 EST 2002
* Skip Montanaro <skip at pobox.com> [2002-12-15 17:01 -0600]:
> > And I want (of course) that this subclassing is 'sticky', so if I do a:
> > x = MyInt(25)
> > x *= 2
>
> > I want 'x' to stay of the class MyInt.
>
> This works for me:
>
> class MyInt(int):
> def __imul__(self, other):
> return MyInt(self*other)
The *= was only meant as an example. 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.
And as Martin pointed out, there's the question if I really want to try
casting to my int subclass if isinstance(other, float), for example.
Gerhard
--
Favourite database: http://www.postgresql.org/
Favourite programming language: http://www.python.org/
Combine the two: http://pypgsql.sf.net/
More information about the Python-list
mailing list