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.

2
  • 3
    Possible duplicate of A python class that acts like dict Commented Mar 25, 2018 at 5:30
  • Any class that implements the special __setitem__ method also supports the object[key] = value syntax. Commented Mar 25, 2018 at 5:31

1 Answer 1

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.

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

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.