subclassing float (or not)
Steven Majewski
sdm7g at virginia.edu
Tue Feb 26 16:10:29 EST 2002
On Tue, 26 Feb 2002, Thomas Heller wrote:
> It seems you always end up with implementing something like
>
> class F(float):
> # float subclass
> def __mul__(self, other):
> return F(float(self) * other, ...)
>
> or
>
> class F:
> # container class with a float instance variable
> def __mul__(self, other):
> return F(self.float * other, ...)
>
> The only *real* difference seems that you can pass float
> subclass instances to round(), log(), and these kind of functions.
> As you already noted, normally they return the wrong results ;-(
>
Well -- the other main advantage of subclassing float is that you
can do: 'isinstance( myFloatType( 1.0 ), float )' and get true.
The other shortcut it gives you is that coercing to float or
int works without you having to actually write a coerce method:
int( myFloatType( 1.0 ) ) --> 1
There may be other things lurking there that automatically work
correctly, that wouldn't if you used a container class. If you
subclass float instead, you don't have to wait around to see
what else breaks because you forgot to implement a method to
support it!
-- Steve
More information about the Python-list
mailing list