Hello. I feel like this question has already been asked and answered, yet I couldn't find anything on-topic, so excuse me if it is so. I want to define the behaviour of [] brackets when applied to class, similar to def []=() construct in ruby, so that calling Python obj['foo'] would actually call some [](self, what) method. How can I do that?
views:
140answers:
4
+6
A:
This is done with __getitem___ in Python.
Here is a list of all the operators: http://docs.python.org/library/operator.html
Lennart Regebro
2009-09-29 18:26:39
Thanks for linking the entire list of operators. It eluded me, and probably many others.
vgm64
2009-10-01 04:36:04
+4
A:
define a method in your class with __getitem__(key) and __setitem__(key, value)
Ayman
2009-09-29 18:28:13
+3
A:
http://docs.python.org/reference/datamodel.html
Section 3.4 in the above link shows you all or most of the operators you can overload in Python. The one you want to overload is
__getitem__()
FModa3
2009-09-29 18:29:13