Overloading + to support tuples

2024/9/23 10:25:51

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 =)

Answer

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.

Probably the best you can get is

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)
https://en.xdnf.cn/q/71837.html

Related Q&A

Extracting particular text associated value from an image

I have an image, and from the image I want to extract key and value pair details.As an example, I want to extract the value of "MASTER-AIRWAYBILL NO:" I have written to extract the entire te…

Installing pip in Pycharm 2016.3

I upgraded to the new version of Pycharm. In the terminal, it says bash-3.2$ instead of my username. When I tried to install a library, it said that pip command is not found:bash: pip: command not foun…

How to store real-time chat messages in database?

I am using mysqldb for my database currently, and I need to integrate a messaging feature that is in real-time. The chat demo that Tornado provides does not implement a database, (whereas the blog does…

Selectively import from another Jupyter Notebook

I arranged my Jupyter notebooks into: data.ipynb, methods.ipynb and results.ipynb. How can I selectively import cells from data and methods notebooks for use in the results notebook?I know of nbimport…

supervisord event listener

Im trying to configure an event listener for supervisord but cant get it to work. I just want to listen for PROCESS_STATE changes and run some python code triggering an urllib2request.In my .conf I hav…

Integration of Java and Python Code in One Eclipse Project

I am writing a compiler in Python using Eclipse with PyDev. Ive come to a stage where I needed to write some code in Java. Im wandering if there is a way of combining these into a single project, bec…

formatting of timestamp on x-axis

Im trying to format the x-axis in my weather data plot. Im happy with the y-axis but all my tries to get the x-axis into a decent, human-readable format didnt work so far. So after several hours of tri…

How can I set the row height in Tkinter TreeView?

I wrote a small app recently that needs to be cross-platform. I used Python and Tkinter for the GUI.It works great but recently I got a new laptop with a hiDPI screen and it seems to mess up the TreeVi…

Is replace row-wise and will overwrite the value within the dict twice?

Assuming I have following data set lst = [u, v, w, x, y] lst_rev = list(reversed(lst)) dct = dict(zip(lst, lst_rev))df = pd.DataFrame({A:[a, b, a, c, a],B:lst},dtype=category)Now I want to replace the …

Python requests, how to add content-type to multipart/form-data request

I Use python requests to upload a file with PUT method.The remote API Accept any request only if the body contains an attribute Content-Type:i mage/png not as Request Header When i use python requests…