Python Forum

Full Version: Redefine __add__ for ints
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Is it possible (for educational purposes), to redefine the behavior of a method such as __add__ for the int class? I know that one can modify _add__ for a custom object but I want to know, for my edification only, whether I could, for example, change simple integer addition to be subtraction. That is, where typing 6+5 would result in 1 (rather than 11). Please don't ask why anyone would want to do this, it is merely to understand some of the underlying structure of Python. Thanks.
I know this can be done in classes, example
class number():
    def __init__(self, value):
        self.value = value

    def __add__(self, num):
        return self.value + num
It's called operator overloading

To use it you could do -
nine = number(9)
print(nine + 9)
But you can't directly override int.__add__. Python prevents you from doing that, it causes a TypeError. I don't think you could do it without getting into the implementation code.
I don't believe the previous answer addressed your question, for which I believe the short answer is no. It's called "monkey patching" and Python will probably never have it because it can lead to spaghetti code.
Thanks for the replies. I had pretty much concluded it was not possible (although it is possible in OO languages such as Smalltalk and Lisp) but I wanted to be sure.