简体   繁体   English

内置不可变类型的子类友好版本?

[英]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. 通常,您需要一个行为与int或float完全相同的类型,除非强制转换为字符串时会产生格式为HH:MM:SS或类似的字符串。

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. 因为操作的结果将是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? 为什么在这些情况下,标准库中没有子类友好的UserInt,UserFloat类型?

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? 这会解决你的问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM