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 class 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__()