我有一个 python 类来计算使用“Kb”、“Mb”或“Gb”表示法指定的位数。我分配了 @property
到bits()
方法,因此它将始终返回 float
(因此与 int(BW('foo').bits)
配合良好)。
但是,当纯类实例被转换为 int()
时,我无法弄清楚该怎么做。 ,如int(BW('foo'))
。我已经定义了__repr__()
返回一个字符串,但当类实例转换为类型时,似乎没有触及该代码。
有什么方法可以在我的类中检测到它正在被转换为另一种类型(从而允许我处理这种情况)?
>>> from Models.Network.Bandwidth import BW
>>> BW('98244.2Kb').bits
98244200.0
>>> int(BW('98244.2Kb').bits)
98244200
>>> BW('98244.2Kb')
98244200.0
>>> type(BW('98244.2Kb'))
<class 'Models.Network.Bandwidth.BW'>
>>>
>>> int(BW('98244.2Kb'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'BW'
>>>
最佳答案
关于python - 如何检测我的 python 类实例是否被转换为整数或 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7403510/