0

My class example:

class Ff(float):
    def __str__(self):
        return '{:.2f}'.format(self) + '$'

a = Ff(1)
print(type(a))
print(a)

Return:

<class '__main__.Ff'>
1.00$

But in case:

a = Ff(1) + 2
print(type(a))
print(a)

Return:

<class 'float'>
3.0

How to in case add Ff(1) + 2 or for radd 2 + Ff(1) get same <class 'main.Ff'> in result?

Vyacheslav
  • 77
  • 10
  • 1
    Implement the `__add__` method and related methods to return your custom subtype… – deceze Feb 08 '21 at 09:36
  • yes, implement `__add__` to be abel to do `Ff(1) + 2`. but you also need to implement `__radd__` to be able to do `2 + Ff(1)` – Nullman Feb 08 '21 at 09:39
  • I must override all arithmetic methods for this? Looks not so optimal.. In my case when I try implement __add__ I received: `RecursionError: maximum recursion depth exceeded`. Have you example? – Vyacheslav Feb 08 '21 at 09:59
  • Yeah, you'll get into some awkwardness if you try to do `+` within `__add__` on two objects that override `__add__`… Subclassing `float` directly might not be a good idea for this reason. You may want to have a look at https://pypi.org/project/money/ for example. – deceze Feb 08 '21 at 10:13

0 Answers0