Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #19671 > unrolled thread
| Started by | Emmanuel Mayssat <emayssat@gmail.com> |
|---|---|
| First post | 2012-01-31 16:54 -0800 |
| Last post | 2012-01-31 16:54 -0800 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
'class' named tuple Emmanuel Mayssat <emayssat@gmail.com> - 2012-01-31 16:54 -0800
| From | Emmanuel Mayssat <emayssat@gmail.com> |
|---|---|
| Date | 2012-01-31 16:54 -0800 |
| Subject | 'class' named tuple |
| Message-ID | <mailman.5273.1328058001.27778.python-list@python.org> |
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 <module>
i[0] = -1
TypeError: 'LIter' object does not support item assignment
Back to top | Article view | comp.lang.python
csiph-web