Re: 'class' named tuple
On 1 February 2012 00:54, Emmanuel Mayssat wrote: > I have the following program. > I am trying to have index the attributes of an object using __getitem__. > Reading them this way works great, but assigning them a value doesn't > Is there a way to do such a thing? > (Almost like a named tuple, but with custom methods) > > class LIter(object): > def __init__(self,parent=None): > super(LIter, self).__init__() > self.toto = 3 > self.tata = 'terto' > Add _attrs = 'toto', 'tata' def __getitem__(self, index): return getattr(self, _attrs[index]) def __setitem__(self, index, value) setattr(self, _attrs[index], value) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: 'class' named tuple
On Tue, Jan 31, 2012 at 5:54 PM, Emmanuel Mayssat wrote: > I have the following program. > I am trying to have index the attributes of an object using __getitem__. > Reading them this way works great, but assigning them a value doesn't > Is there a way to do such a thing? For assignment, use __setitem__. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
'class' named tuple
I have the following program. I am trying to have index the attributes of an object using __getitem__. Reading them this way works great, but assigning them a value doesn't Is there a way to do such a thing? (Almost like a named tuple, but with custom methods) class LIter(object): def __init__(self,parent=None): super(LIter, self).__init__() self.toto = 3 self.tata = 'terto' def __getitem__(self,index): if index == 0 : return self.toto if index == 1 : return self.tata # [other methods] if __name__ == "__main__": i = LIter() print i[0] print i[1] i.toto = 2 i.tata = 'bye' print i[0] print i[1] i[0] = -1 i[1] = 'salut' print i[0] print i[1] $ python iter.py 3 terto 2 bye Traceback (most recent call last): File "iter.py", line 25, in i[0] = -1 TypeError: 'LIter' object does not support item assignment -- http://mail.python.org/mailman/listinfo/python-list