3

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?

0

4 Answers 4

11

It's all in the docs: __getitem__.

Sign up to request clarification or add additional context in comments.

Comments

7

This is done with __getitem___ in Python.

Here is a list of all the operators: http://docs.python.org/library/operator.html

1 Comment

Thanks for linking the entire list of operators. It eluded me, and probably many others.
5

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

Comments

4

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__()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.