mrCarnivore
mrCarnivore

Reputation: 5068

Overloading [] operator in python?

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]

Upvotes: 1

Views: 115

Answers (1)

Romain Cata
Romain Cata

Reputation: 141

You have to implement the magic method __getitem__ on classname

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

See Python documentation

Upvotes: 4

Related Questions