重载+以支持元组

Clé*_*ent 5 python tuples operator-overloading

我希望能在python中编写类似的东西:

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

我意识到你可以重载运算符来使用自定义类,但有没有办法让运算符重载对?

当然,这样的解决方案

c = tuple([x+y for x, y in zip(a, b)])
Run Code Online (Sandbox Code Playgroud)

做得好,但是,抛开性能,它们并不像+运营商那样漂亮.

当然可以定义addmul运行诸如

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

def mul(a, (x, y)):
    return (a * x, a * y)
Run Code Online (Sandbox Code Playgroud)

但仍然能够写q * b + r而不是add(times(q, b), r)更好.

想法?

编辑:在旁注中,我意识到,由于+目前映射到元组连接,重新定义它可能是不明智的,即使它是可能的.问题仍然存在-例如=)

Sve*_*ach 6

与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)
Run Code Online (Sandbox Code Playgroud)