dopatraman
dopatraman

Reputation: 13908

what is the dict class used for

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.

Upvotes: 4

Views: 316

Answers (3)

KL-7
KL-7

Reputation: 47618

If you're not familiar with inheritance concept of object-oriented programming have a look at least at this wiki article (though, that's only for introduction and may be not for the best one).

In python we use this syntax to define class A as subclass of class B:

class A(B):
  pass # empty class

In your example, as FileInfo class is inherited from standard dict type you can use instances of that class as dictionaries (as they have all methods that regular dict object has). Besides other things that allows you assign values by key like that (dict provides method for handing this operation):

self['name'] = filename

Is that the explanation you want or you don't understand something else?

Upvotes: 3

Hossein
Hossein

Reputation: 4137

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.

# From the example on the next section
>>> f = fileinfo.FileInfo("/music/_singles/kairo.mp3")
>>> f["name"]
'/music/_singles/kairo.mp3'

The fileinfo class 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:

def __setitem__(self, key, item):
    self.data[key] = item
    if key == "sensor":
        print("Sensor activated!")

Or for example you want to return a special value each time user reads the 'temperature' key. For this you subclass a __getitem__ function:

def __getitem__(self, key):
    if key == "temperature":
        return CurrentWeatherTemperature()
    else:
        return self.data[key]

Upvotes: 1

tkone
tkone

Reputation: 22728

When an Class in Python inherits from another Class, it means that any of the methods defined on the inherited Class are, by nature, defined on the newly created Class.

So when FileInfo inherits dict it means all of the functionality of the dict class is now available to FileInfo, in addition to anything that FileInfo may declare, or more importantly, override by re-defining the method or parameter.

Since the dict Object in Python allows for key/value name pairs, this enables FileInfo to have access to that same mechanism.

Upvotes: 1

Related Questions