Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : Operator Overloading a specific type

I'd like to be able to have the operator of my class interact with regular types in a way that I define. Lets 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 just fine, but now if I try to do:

print a+2

I get an error since an int does not have a member named x. How do I define Mynum + int in the class? This sounds like a job for decorators or metaclasses, but I'm terribly unfamiliar with their usage. This question seems similar, but not quite identical.

like image 308
Hooked Avatar asked Jul 06 '10 17:07

Hooked


People also ask

Which operators can be overloaded in Python?

Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well.

What is the most popular form of operator overloading in Python?

A very popular and convenient example is the Addition (+) operator. Just think how the '+' operator operates on two numbers and the same operator operates on two strings. It performs “Addition” on numbers whereas it performs “Concatenation” on strings.

Which function overloads == in Python?

Python does not support function overloading. When we define multiple functions with the same name, the later one always overrides the prior and thus, in the namespace, there will always be a single entry against each function name.


2 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))
like image 80
SilentGhost Avatar answered Sep 28 '22 10:09

SilentGhost


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
like image 23
unutbu Avatar answered Sep 28 '22 12:09

unutbu