Hanfei Sun
Hanfei Sun

Reputation: 47051

how to re-define the `__add__` method for `int`?

I want to re-define the __add__ method for int so that the usage would be like this:

 >> 1+2
 => "1 plus 2"

 >> (1).__add__(2)
 => "1 plus 2"

I tried this:

 >>> int.__add__ = lambda self, x: str(self)+" plus " + str(x)

However, it throws an exception:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'int'

Does anyone have ideas about why I can't redefine the __add__ method like this? And is there other way to do this?

Upvotes: 0

Views: 539

Answers (2)

Pradhyum R
Pradhyum R

Reputation: 113

Although not best practice, you could use forbiddenfruit to overwrite the __add__ method. Usage:

>>> from forbiddenfruit import curse
>>> curse(int, '__add__', lambda x, y: f"{x} plus {y}")
>>> 1 + 2
'1 plus 2'

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

create your own class which overrides the __add__ method of int class.

In [126]: class myint(int):
    def __add__(self,a):
        print "{0} plus {1}".format(self,a)
   .....:         

In [127]: a=myint(5)

In [128]: b=myint(6)

In [129]: a+b
5 plus 6

Upvotes: 3

Related Questions