[英]How can I detect whether my python class instance is cast as an integer or float?
我有一个python类来计算使用“ Kb”,“ Mb”或“ Gb”表示法指定的位数。 我为bits()
方法分配了一个@property
,因此它将始终返回一个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'
>>>
基本上,您想要的是位于Models.Network.Bandwidth.BW类的__trunc__
和__float__
中:
#!/usr/bin/python
class NumBucket:
def __init__(self, value):
self.value = float(value)
def __repr__(self):
return str(self.value)
def bits(self):
return float(self.value)
def __trunc__(self):
return int(self.value)
a = NumBucket(1092)
print a
print int(a)
print int(a.bits())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.