Search code examples
pythonself

Confused by self["name"] = filename


I'm currently reading this amazing book called "Dive into Python". Up to now everything has made sense to me, but the following method has left me with some questions. Its in the chapter about initializing classes:

class FileInfo(UserDict):
    "store file metadata"
    def __init__(self, filename=None):
        UserDict.__init__(self)
        self["name"] = filename

It's only the last line I don't get. The way I see it at the moment, the calling object has a list, whose item "name" is assigned the value of the argument passed. But this doesn't make sense to me, since I thought that you can only access list indices by integers. The book says the following about this line: "You're assigning the argument filename as the value of this object's name key." Is the name key another variable that every object defines (like doc)? And if yes, why can it be accessed like that?


Solution

  • [...] isn't just for lists. Any type can support it, and the index doesn't necessarily have to be an integer. self is the current object, which according to your code derives from UserDict, which supports the item manipulation methods.