Can someone explain what the dict class is used for? This snippet is from Dive Into Python
class FileInfo(dict):
"store file metadata"
def __init__(self, filename=None):
self["name"] = filename
I understand the assignment of key=value pairs with self['name'] = filename but what does inheriting the dict class have to do with this? Please help me understand.
It’s for creating your own customized Dictionary type.
You can override
__init__,__getitem__and__setitem__methods for your own special purposes to extend dictionary’s usage.Read the next section in the Dive into Python text: we use such inheritance to be able to work with file information just the way we do using a normal dictionary.
The
fileinfoclass is designed in a way that it receives a file name in its constructor, then lets the user get file information just the way you get the values from an ordinary dictionary.Another usage of such a class is to create dictionaries which control their data. For example you want a dictionary who does a special thing when things are assigned to, or read from its ‘sensor’ key. You could define your special
__setitem__function which is sensitive with the key name:Or for example you want to return a special value each time user reads the ‘temperature’ key. For this you subclass a
__getitem__function: