python - Is it possible to overload operators for native datatypes? -


for example, if try do:

a_string + an_int 

... a_string type 'str' , an_int type 'int', or:

an_int + a_string 

there typeerror because there no implicit conversion of types. understand if using own subclasses of int , string, able overload __add__() method in classes achieve this.

however, out of curiosity, know: possible overload + operator in class definitions of int , str, __add__(int,str) , __add__(str,int) automatically concatenate them strings?

if not, reasons why programmer should not overload operators native datatype?

in general, without reverting c-level api, cannot modify attributes of builtin types (see here). can, however, subclass builtin types , want on new types. question asked (making addition string based), you'd modify __add__ , __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 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -