From PMOTW, namedtuple instances are just as memory efficient as regular tuples because they do not have per-instance dictionaries. Each kind of namedtuple is represented by its own class, created by using the namedtuple() factory function. The arguments are the name of the new class and a string containing the names of the elements.
1 2 3 4 5 |
import collections as _collections Point = _collections.namedtuple("Point", ("x y z")) print Point(4,5,6) |
>> Point(x=4, y=5, z=6)
In the below code we make use of namedtuple and make class object behave like a list or tuple using __getitem__ and update the value of arguments using __setitem__ .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class PointLocation(object): def __init__(self, x, y, z): self._x = x self._y = y self._z = z self._location = Point(x, y, z) def __repr__(self): return "%s(%r, %r, %r)" % ( self.__class__.__name__, self._x, self._y, self._z, ) def __getitem__(self, key): """ to make the object to be used in a manner similar to a tuple or list """ return self._location.__getitem__(key) def __setitem__(self, key, value): """ update the value of argument like a dictionary """ try: self._location = self._location._replace(**{'xyz'[key]: value}) except IndexError: raise IndexError("%s takes %s has arguments. You are trying to update %s argument." % ( self.__class__.__name__, len(self._location), key) ) |
1 2 3 4 5 6 |
print PointLocation(4,5,6) pointLocationObj = PointLocation(4,5,6) for axis in pointLocationObj: print axis |
>> PointLocation(4, 5, 6) 4 5 6
my discussion with Martijin Pieters on SO: http://stackoverflow.com/questions/30075560/how-to-set-value-of-class-object-argument-as-if-its-a-dict-using-setitem
regarding setting and updating the value of argument.