Rahul Sarma Rahul Sarma - 4 months ago 15
Python Question

What does self[identifier] = some_value do in this code?

I was just trying to learn K-ary tree implementation in Python and came across this link:
http://www.quesucede.com/page/show/id/python-3-tree-implementation

In the tree.py file, there is a section of code like this:

class Tree:

def __init__(self):
self.__nodes = {}

@property
def nodes(self):
return self.__nodes

def add_node(self, identifier, parent=None):
node = Node(identifier)
self[identifier] = node

if parent is not None:
self[parent].add_child(identifier)

return node

# ... ...

def __getitem__(self, key):
return self.__nodes[key]

def __setitem__(self, key, item):
self.__nodes[key] = item


What is
self[identifier]
? Is it a list? This is really confusing.
Can someone explain and/or point me to some documentation of using self as a list?

Answer

In the full example code, this is the important bit:

def __getitem__(self, key):
    return self.__nodes[key]

def __setitem__(self, key, item):
    self.__nodes[key] = item

These two 'magic methods', __getitem__ and __setitem__, allow the class to be accessed like a list or dictionary would be, using the foo[key] syntax.

So, in your case, if foo was a Tree instance, foo["a"] = "b" would execute __setitem__ with key as "a" and item as "b", consequently mapping key to item in the self.__nodes dictionary.