How do I implement a method that overloads float(), i.e. it is called when an instance of a class I’ve written is passed to float()?
I am starting to write my own Fraction class:
class Fraction:
def __init__(self, num = 0, denom = 1):
self.num = float(num)
self.denom = float(denom)
Now I want to be able to do this:
float(Fraction())
I tried using the below method, but that didn’t work.
def float(self):
return self.num / self.denom
Define the
__float__()special method on your class.Note that this method must return a
float! The calculationself.num / self.denom, returns anintby 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.denomfor example.