当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Subclass-friendly versions of built-in inmutable types?

问题描述:

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

class ElapsedTime(float):

def __str__(self):

return 'XXX'

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 [1]: 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 [2]: float2(20.4)
Out[2]: 20.4

In [3]: print float2(20.4)
20:4

In [4]: x = float2(20.4) + float2(10.1)

In [5]: x
Out[5]: 30.5

In [6]: print x
30:5

In [7]: x = float2(20.4) + float(10.1)

In [8]: x
Out[8]: 30.5

In [9]: print x
30:5

does this solve your problem?

分享给朋友:
您可能感兴趣的文章:
随机阅读: