Type conversion of custom class to float

I have a class customInt, which looks something like this:

class customInt:
   def __init__(self, value):
      self.value=int(value)
   def __add__(self, other):
      return foo(self.value+other.value)
      # do some other stuff

obj=foo(1.23)

Is it possible to create an operator/attribute/property/… to cast the object obj to a float, so that it’s possible to cast the class with float(obj)?

The aim of this is to create a drop-in replacement to a normal int, but without the automatic casting to a float in divisions, etc. So, not desired is:

  • A method like obj.to_float(). Then it wouldn’t be a drop-in replacement anymore.
  • Inheritance from a castable type: In this case, I would have to overload every single operator. Which is not ideal.

>Solution :

You can define a def __float__(self): function in your class, and it will be called when you use float(obj). You can also add __int__, __str__ and __complex__ in the same way.

Leave a Reply