Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Redefine __add__ for ints
#1
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.
Reply
#2
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)
Reply
#3
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
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.
Reply
#5
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,454 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  Convert String of an int array to a Numpy array of ints mdsousa 5 5,579 Apr-08-2021, 08:00 PM
Last Post: mdsousa
  Unable to bit shift and logical OR bytes and ints? MysticLord 7 6,818 Sep-01-2020, 03:31 PM
Last Post: deanhystad
  How to redefine object so that all user- objects have the necessary capabilities? AlekseyPython 5 2,979 Mar-03-2019, 04:25 AM
Last Post: AlekseyPython
Bug Random Ints to Str Problem BIGPESH 2 2,095 Aug-18-2018, 12:44 PM
Last Post: BIGPESH
  Reading floats and ints from csv-like file Krookroo 15 19,907 Sep-05-2017, 03:58 PM
Last Post: Krookroo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020