How to overload `float()` for a custom class in Python?

前端 未结 1 775
故里飘歌
故里飘歌 2021-01-17 16:20

Summary

How can I overload the built-in float for my class so when I call float() on an instance of it, my custom function gets called in

1条回答
  •  迷失自我
    2021-01-17 16:46

    Define the __float__() special method on your class.

    class MyClass(object):
        def __float__(self):
             return 0.0
    
    float(MyClass())   # 0.0
    

    Note that this method must return a float! The calculation self.num / self.denom, returns an int by default in versions of Python prior to 3.0 assuming both operands are integers. In this case you'd just make sure one of the operands is a float: float(self.num) / self.denom for example.

    0 讨论(0)
提交回复
热议问题