0

I am newbie to python object oriented programming. I am trying to understand binary tree implantation code using python.

My understanding is object.method is the way to call the function. But here the object is called as object[key]="value" without explicitly calling the function like object.put("key","value) . Please help me to understand this code.

Narendra
  • 1,511
  • 1
  • 10
  • 20
  • 3
    Possible duplicate of [A python class that acts like dict](https://stackoverflow.com/questions/4014621/a-python-class-that-acts-like-dict) – Aran-Fey Mar 25 '18 at 05:30
  • Any class that implements the special `__setitem__` method also supports the `object[key] = value` syntax. – Aran-Fey Mar 25 '18 at 05:31

1 Answers1

3

Like many languages that support object-oriented programming, Python has operators that can be overloaded by different classes as appropriate.

For example, when you write x + y, that calls x.__add__(y) (slightly oversimplified, but not in ways that are relevant here).

The [] here is just another operator. When you write object[key]="value", that calls object.__setitem__(key, "value").

So, you are doing object-oriented method calling, just with a little bit of syntactic sugar on top to make it more readable.

abarnert
  • 354,177
  • 51
  • 601
  • 671