15

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
9
  • @DavidHeffernan Could you do me a favour? My question here: stackoverflow.com/questions/9938329/… had gotten closed for being to vague. I edited it and now it seems like a perfectly legit question for SO. Aug 19, 2012 at 15:14
  • Thing is, my account just got automatically banned because of that and I can't ask any more questions, so could you please upvote it if you think my question is good enough? Aug 19, 2012 at 15:15
  • @DavidHeffernan ??? Atleast a reply saying "Yes" or "No"? Aug 19, 2012 at 15:34
  • yeah, +1, looks a fair Q to me Aug 19, 2012 at 15:56
  • @DavidHeffernan Thanks a lot. If it wouldn't be too much, could you also flag the question for moderator's attention so it can be reopened? ( Apparently, that privilege has been stripped too :< ) Aug 19, 2012 at 16:07

1 Answer 1

27

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.

6
  • I am using ints throughout my code for self.num and self.denom. 10x for the answer. Apr 5, 2012 at 19:31
  • What would happen if you didn't return a float? Apr 5, 2012 at 19:32
  • 1
    You get a TypeError exception.
    – kindall
    Apr 5, 2012 at 19:35
  • 1
    @YatharthROCK: Basically, you will create an unstable black hole inside your python interpreter and the universe will be destroyed. I think kindall is just pointing out the fact that / denotes integer division by default in <= python 2.x and floating point division in python 3.x. You should be aware of this. Apr 5, 2012 at 19:38
  • 1
    @kindall: So when you call one of the special methods, it doesn't just execute the overloaded method, it still passes through the special method? Apr 5, 2012 at 19:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.