It is designed to create your own custom dictionary type.
You can override the __init__ , __getitem__ and __setitem__ methods for your special purposes to expand the use of the dictionary.
Read the next section in the Dive text in Python: we use such inheritance to be able to work with file information in the same way as we use a regular dictionary.
# From the example on the next section >>> f = fileinfo.FileInfo("/music/_singles/kairo.mp3") >>> f["name"] '/music/_singles/kairo.mp3'
The fileinfo class fileinfo designed in such a way that it receives the file name in its constructor, and then allows the user to get information about the file only as you get values from a regular dictionary.
Another use of this class is to create dictionaries that control their data. For example, you need a dictionary that does a particular thing when something is assigned, or read its "sensor" key. You can define a special function __setitem__ that is sensitive to 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 every time the user reads "temperature". To do this, you subclass the __getitem__ function:
def __getitem__(self, key): if key == "temperature": return CurrentWeatherTemperature() else: return self.data[key]
source share