简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM