How to define [] for a class in Python?

It seems to me that this question has already been asked and answered, but I could not find anything on the topic, so excuse me if this is so. I want to determine the behavior of the brackets [] when applied to a class, similar to the construction def []=()in ruby, so that calling Python obj['foo']will actually call some method [](self, what). How can i do this?

+3
source share
4 answers

All of this in the documents __getitem__.

+11
source

This is done using __getitem___in Python.

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

+7
source

__getitem__(key) __setitem__(key, value)

+5
+4
source

Source: https://habr.com/ru/post/1718839/


All Articles