重载+支持元组 [英] Overloading + to support tuples
问题描述
我希望能够在python中编写如下内容:
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.
当然可以定义add
和mul
函数,例如
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)
但仍然能够写q * b + r
而不是add(times(q, b), r)
会更好.
but still being able to write q * b + r
instead of add(times(q, b), r)
would be nicer.
想法?
编辑:从侧面说明,我意识到由于+
当前映射到元组串联,因此即使有可能重新定义它也是不明智的.这个问题仍然存在于-
,例如=)
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 =)
推荐答案
与Ruby相比,您无法更改Python中内置类型的行为.您所能做的就是从内置类型创建一个新的 derived 类型.不过,文字仍然会创建内置类型.
In contrast to Ruby, you can't change the behaviour of built-in types in Python. All you can do is create a new type derived from a built-in type. Literals will still create the built-in type, though.
可能最好的是
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)
这篇关于重载+支持元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!