[英]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.