Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading