How can I detect whether my python class instance is cast as an integer or float?
I have a python class to calculate the number of bits when they have been specified using "Kb", "Mb" or "Gb" notation.  I assigned a @property to the bits() method so it will always return a float (thus working well with int(BW('foo').bits)).
However, I am having trouble figuring out what to do when a pure class instance is cast as an int(), such as int(BW('foo')).  I have already defined __repr__() to return a string, but it seems that that code is not touched when the class instance is cast to a type.
Is there any way to detect within my cl开发者_StackOverflow社区ass that it is being cast as another type (and thus permit me to handle this case)?
>>> 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'
>>>
Read this
http://docs.python.org/reference/datamodel.html#emulating-numeric-types
__int__()
__float__()
Basically what you want lies within overriding __trunc__ and __float__ in the Models.Network.Bandwidth.BW class:
#!/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())
 加载中,请稍侯......
      
精彩评论