Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend python build-in class: float

Tags:

python

class

I would like to change the

float.__str__ 

function of the build in float type (python 2)

I tried to extend this class.

class SuperFloat(float):
    def __str__(self):
        return 'I am' + self.__repr__()

However, when I add it it becomes a normal float

egg = SuperFloat(5)
type(egg+egg)

returns float

My ultimate goal is that also

egg += 5

stays a superfloat

like image 429
Vasco Avatar asked Dec 20 '22 12:12

Vasco


2 Answers

You will need to override the "magic methods" on your type: __add__, __sub__, etc. See here for a list of these methods. unutbu's answer shows how to do this for __add__ and __radd__, but there are a lot more you will have to override if you want your subclass to be substitutable for the builtin type in any situation. This page has some suggestions on how to make some of that work easier.

like image 74
BrenBarn Avatar answered Jan 02 '23 06:01

BrenBarn


class SuperFloat(float):
    def __str__(self):
        return 'I am ' + self.__repr__()
    def __add__(self, other):
        return SuperFloat(super(SuperFloat, self).__add__(other))
    __radd__ = __add__

In [63]: type(5+egg)
Out[63]: __main__.SuperFloat

In [64]: type(egg+5)
Out[64]: __main__.SuperFloat

In [65]: type(egg+egg)
Out[65]: __main__.SuperFloat

In [67]: egg += 5

In [69]: type(egg)
Out[69]: __main__.SuperFloat
like image 41
unutbu Avatar answered Jan 02 '23 07:01

unutbu