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.
JavaScript
x
4
1
class Point(namedtuple("Point", "x y")):
2
def __add__(self, other):
3
return Point(x = self.x + other.x, y = self.y + other.y)
4
If we use this functionality:
JavaScript
1
2
1
print(Point(x = 1, y = 2) + Point(x = 3, y = 1))
2
The result is:
JavaScript
1
2
1
Point(x=4, y=3)
2
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:
JavaScript
1
5
1
class Point(namedtuple("Point", "x y")):
2
def __add__(self, other):
3
return Point(**{field: getattr(self, field) + getattr(other, field)
4
for field in self._fields})
5