Python: Overload operator of a specific type

I would like the operator of my class to interact with regular types in the way that I define. Say, for example, I have:

class Mynum(object):
  def __init__(self, x):
   self.x = x
  def __add__(self, other):
   return self.x + other.x

a = Mynum(1)
b = Mynum(2)

print a+b

This works fine, but now if I try to do:

print a+2

I am getting an error because it intdoes not have a member with a name x. How to define Mynum+ intin a class? It sounds like work for decorators or metaclasses, but I'm terribly unfamiliar with using them. This question seems similar, but not exactly identical.

+5
source share
3 answers
def __add__(self, other):
    if isinstance(other, self.__class__):
        return self.x + other.x
    elif isinstance(other, int):
        return self.x + other
    else:
        raise TypeError("unsupported operand type(s) for +: '{}' and '{}'").format(self.__class__, type(other))
+11
source
class Mynum(object):
    def __init__(self, x):
        self.x = x
    def __add__(self, other):
        try:
            return self.x + other.x
        except AttributeError:
            return self.x + other
    __radd__=__add__

a = Mynum(1)
b = Mynum(2)

print(a+b)
# 3
print(a+2)
# 3
print(2+a)
# 3
+4
source

/ ? :

class MyNum(object):
    def __init__(self, x):
        self.x = x
    def __add__(self, other):
        return other + self.x
    __radd__ = __add__
x = MyNum(5)
y = MyNum(6)
print x + 2
7
print 2 + x
7
print x + y
11
print y + x
11
+2

All Articles