This is such a common scenario when you just want to use a built-in type
only with a different string representation. For instance, consider a
variable to store time measurements. Typically you want a type that behaves
exactly like int or float for all intents and purposes except that when
coerced to string would produce a string formatted as HH:MM:SS or something like that.
It should be easy. Unfortunately the following doesn't work
because the result of operations will be type float. The
solution I know is rewrite a couple dozen methods, but this is most
impractical. I can't believe there is no other way. Why is there no
subclass-friendly UserInt, UserFloat types in the standard library intended to be
used in these situations?
In : class float2(float): ...: def __init__(cls,val): ...: return float.__init__(cls,val) ...: def __str__(cls): ...: return str(cls.real).replace(".",":") ...: def __add__(cls,other): ...: return float2(cls.real + other.real) ...: ## similarly implement other methods... ...: In : float2(20.4) Out: 20.4 In : print float2(20.4) 20:4 In : x = float2(20.4) + float2(10.1) In : x Out: 30.5 In : print x 30:5 In : x = float2(20.4) + float(10.1) In : x Out: 30.5 In : print x 30:5
does this solve your problem?