flobue
flobue

Reputation: 69

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:

Upvotes: 0

Views: 417

Answers (1)

charon25
charon25

Reputation: 316

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.

Upvotes: 2

Related Questions