3 ms·
I'm a huge fan of a namedtuple; I'm always surprised not to see it used more. And in cases where you really do need class-like behaviour, it's easy to extend i
by mikepurvis 15y ago
I'm a huge fan of a namedtuple; I'm always surprised not to see it used more.
And in cases where you really do need class-like behaviour, it's easy to extend it with additional methods or operators, while still getting all the other convenience stuff for free:
class Point3D(namedtuple('Point3D', "x y z")):
def __add__(self, other):
if other.__class__ != self.__class__:
raise TypeError
return self.__class__(*[a+b for a,b in zip(self, other)])
print Point3D(1, 2, 3) + Point3D(5, 4, 2)
- kisielk 15y agoBeware that once you subclass namedtuple you are losing out on one of its beneficial characteristics: memory efficiency. Instances of subclasses have an instance dict which has a non-trivial overhead. You can avoid this by defining __slots__ again in the subclass.