Anton Anton - 7 months ago 22
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
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
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
, so that
automatically concatenate them as strings?

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


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

>>> 3 + Int(5) + 87