Confused by self ["name"] = file name

I am currently reading this wonderful book called "Immersion in Python". So far, everything has made sense to me, but the following method has left me with some questions. Its in the chapter on class initialization:

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

This is just the last line that I am not getting. The way I see it at the moment, the caller has a list whose element "name" is assigned the value of the argument passed. But for me this does not make sense, since I thought you could only access the list indices with integers. The book says the following about this line: "You assign the file name of the argument as the value of this key to the name of the object." Is the key of a key another variable that each object defines (e.g. doc )? And if so, why can it be accessed?

+3
source share
5 answers

[...] . , . self - , UserDict, .

+6

, class FileInfo(UserDict), , self['name'] = filename

+2

UserDict, , , . dicts ( dict) self dict, self[key] = value

+2

UserDict, __getitem__(), , :

self["name"] = filename  # Associate the filename with the "name" key.
+2

No, an object selfis a subclass UserDictthat is a hash table form (known as a dictionary or dictin Python). The last line just creates a key "name"for the file name.

+2
source

Source: https://habr.com/ru/post/1773476/


All Articles