Anton Anton - 3 months ago 10
Python Question

Is it possible to overload operators for native datatypes?

For example, if I try to do:

a_string + an_int


... where a_string is type 'str' and an_int is type 'int', or:

an_int + a_string


There would be a
TypeError
because there is no implicit conversion of the types. I understand that if I were using my own subclasses of int and string, I would be able to overload the
__add__()
method in my classes to achieve this.

However, out of curiosity, I would like to know: would it be possible to overload the + operator in the class definitions of
int
and
str
, so that
__add__(int,str)
and
__add__(str,int)
automatically concatenate them as strings?

If not, what are the reasons why a programmer should not overload the operators for a native datatype?

Answer

In general, without reverting to the C-level API, you cannot modify attributes of builtin types (see here). You can, however, subclass builtin types and do what you want on the new types. For the question you specifically asked (making the addition string based), you'd modify __add__ and __radd__:

class Int(int):
    def __add__(self, other):
        return Int(int(str(self) + str(other)))

    def __radd__(self, other):
        return Int(str(other) + str(self))

>>> Int(5) + 3
53

>>> 3 + Int(5) + 87
3587