Overload + to support tuples

I would like to write something like this in python:

a = (1, 2)
b = (3, 4)
c = a + b # c would be (4, 6)
d = 3 * b # d would be (9, 12)

I understand that you can overload statements to work with custom classes, but is there a way to overload statements to work with pairs?

Of course, solutions like

c = tuple([x+y for x, y in zip(a, b)])

really work, but, dropping the performance, they are not as good as operator overload +.

Of course, you can define functions addand mul, such as

def add((x1, y1), (x2, y2)):
    return (x1 + x2, y1 + y2)

def mul(a, (x, y)):
    return (a * x, a * y)

but still the opportunity to write q * b + rinstead add(times(q, b), r)will be more pleasant.

Ideas?

. , , + , , . - - =)

+5
7

Ruby, Python. , , , . .

, , ,

class T(tuple):
    def __add__(self, other):
        return T(x + y for x, y in zip(self, other))
    def __rmul__(self, other):
        return T(other * x for x in self)
a = T((1, 2))
b = T((3, 4))
c = a + b # c would be (4, 6)
d = 3 * b # d would be (9, 12)
+5

tuple __add__. :

class mytuple(tuple):
    def __add__(self, other):
        assert len(self) == len(other)
        return tuple([x + y for x, y in zip(self, other)])

mt = mytuple((5, 6))
print mt + (2, 3)  # prints (7, 9)

, . , numpy.

+3

, C, . NumPy, , .

+2

python, , , .

a = 1 + 2j
b = 3 + 4j
c = a + b # c would be 4 + 6j
d = 3 * b # d would be 9 + 12j

.

, ,

class T(tuple):
    def __add__((x, y), (x1, y1)):
        return T((x+x1, y+y1))
    def __rmul__((x, y), other):
        return T((other * x, other * y))

, .

+2

--, :

x = Infix(lambda a,b:tuple([x+y for x, y in zip(a, b)]))
y = Infix(lambda a,b:tuple([a*y for y in b]))

c = a |x| b # c would be (4, 6)
d = 3 |y| b # d would be (9, 12) 

This will hide the expressions of the generator and is applicable to tuples of all lengths, due to the "strange" pseudo-operators |x|and |y|.

+2
source

Write your own class and implement __mul__, __add__, etc.

+1
source

You can use numpy.arrayto get everything you need.

+1
source

All Articles