1

Is it possible to overload the [] operator in python?

I want to access a method of a class by calling classname[elementname] (like in a dict). This might seem unneccessary but the class encapsulates a database element with children that also have children that also have children that... You get the point.

If I know which child from the 3rd inheritance step I want to get I could then instead of:

classnname.getChild(childname1).getChild(childname2).getChild(childname3)

use the shorter and cleaner:

classnname[childname1][childname2][childname3]
4
  • 3
    __getitem__ Commented Dec 14, 2017 at 16:53
  • @kindall: Thanks that totally works! Why was I not able to find this with a google/stackoverflow search? Commented Dec 14, 2017 at 16:56
  • Don't know; what were you searching for? The first Google result for Python operator overload has the information you seek. Commented Dec 14, 2017 at 17:00
  • That first hit I did find and read and there was no __getitem__ in that site... Maybe I was looking for the wrong things. Thanks again for your quick help! Commented Dec 14, 2017 at 17:04

1 Answer 1

4

You have to implement the magic method __getitem__ on classname

class classname:
    def __getitem__(self, key):
        return self.getChild(key)

See Python documentation

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.