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?
Add a comment
|
4 Answers
This is done with __getitem___ in Python.
Here is a list of all the operators: http://docs.python.org/library/operator.html
1 Comment
physicsmichael
Thanks for linking the entire list of operators. It eluded me, and probably many others.
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__()