简体   繁体   中英

Extend python build-in class: float

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM