tags:

views:

140

answers:

4

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?

+12  A: 

It's all in the docs: __getitem__.

PiotrLegnica
+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
Thanks for linking the entire list of operators. It eluded me, and probably many others.
vgm64
+4  A: 

define a method in your class with __getitem__(key) and __setitem__(key, value)

Ayman
+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