How to add 2 objects and return number, in Python?

Asked

Viewed 115 times

-2

I have the following class:

class num(int):
    def __init__(self, n):
        self.n = n

I would like it to work as follows:

A = num(2)
B = num(3)
A + B = 5

This is part of a much more complex personal project. I have already researched the Builtin functions, up to the add and str and nothing. Please help me!

  • 2

    And why the __add__ does not satisfy your need?

1 answer

0


You can implement the method __radd__ in your class:

class num(int):
     def __init__(self, n):
         self.n = n
     def __radd__(self, other):
        if isinstance(other, num):
            return self.n + other.n
        else:
            return self.n + other

a = num(1)
b = num(2)
print(a + b) # 3
print(3 + a) # 4
print(a + 4) # 5
  • Thank you so much! There are still good people in this world! hahaha

  • It would be better to return a new instance of num with the attribute n equal to the sum of the values, and not only the sum of the values themselves.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.