I'd like to be able 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 realize that you can overload operators to work with custom classes, but is there a way to overload operators to work with pairs?
Of course, such solutions as
c = tuple([x+y for x, y in zip(a, b)])
do work, but, let aside performance, they aren't quite as pretty as overloading the +
operator.
One can of course define add
and mul
functions 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 being able to write q * b + r
instead of add(times(q, b), r)
would be nicer.
Ideas?
EDIT: On a side note, I realize that since +
currently maps to tuple concatenation, it might be unwise to redefine it, even if it's possible. The question still holds for -
for example =)