gpt4 book ai didi

python - 如何检测我的 python 类实例是转换为整数还是 float ?

转载 作者:行者123 更新时间:2023-11-28 22:04:19 25 4
gpt4 key购买 nike

我有一个 python 类来计算使用“Kb”、“Mb”或“Gb”表示法指定的位数。我将 @property 分配给 bits() 方法,因此它将始终返回一个 float(因此与 int(BW ('foo').bits)).

但是,当将纯类实例转换为 int() 时,我无法弄清楚该怎么做,例如 int(BW('foo'))。我已经定义了 __repr__() 来返回一个字符串,但是当类实例被转换为一个类型时,似乎没有触及该代码。

有什么方法可以在我的类(class)中检测到它被转换为另一种类型(从而允许我处理这种情况)?

>>> 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com