Is there a more pythonic way to implement elementwise addition for named tuples?
Using this class that inherits from a namedtuple generated class named “Point I can do elementwise addition for this specific named tuple.
class Point(namedtuple("Point", "x y")): def __add__(self, other): return Point(x = self.x + other.x, y = self.y + other.y)
If we use this functionality:
print(Point(x = 1, y = 2) + Point(x = 3, y = 1))
The result is:
Point(x=4, y=3)
Is there a more pythonic way to do this in general? Is there a generalized way to do this that can extend elementwise addition to all namedtuple generated objects?
Advertisement
Answer
This is a possible solution:
class Point(namedtuple("Point", "x y")): def __add__(self, other): return Point(**{field: getattr(self, field) + getattr(other, field) for field in self._fields})