简体   繁体   English

什么是dict类用于

[英]what is the dict class used for

Can someone explain what the dict class is used for? 有人能解释一下dict类的用途吗? This snippet is from Dive Into Python 这个片段来自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? 我理解key = value对的赋值与self['name'] = filename但是继承dict类有什么用呢? Please help me understand. 请帮我理解。

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). 如果你不熟悉继承概念,面向对象编程至少要看一下这篇 wiki文章(不过,这只是为了介绍,可能不是最好的一篇)。

In python we use this syntax to define class A as subclass of class B : 在python中,我们使用此语法将类A定义为类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). 在您的示例中,由于FileInfo类是从标准dict类型继承的,因此您可以将该类的实例用作字典(因为它们具有常规dict对象具有的所有方法)。 Besides other things that allows you assign values by key like that ( dict provides method for handing this operation): 除了允许你按键分配值的其他东西( dict提供了处理此操作的方法):

self['name'] = filename

Is that the explanation you want or you don't understand something else? 这是你想要的解释还是你不明白别的什么?

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. 当Python中的Class继承自另一个Class时,它意味着继承的Class上定义的任何方法本质上都是在新创建的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. 因此,当FileInfo继承dict它意味着除了FileInfo可能声明的任何内容之外, dict类的所有功能现在都可用于FileInfo ,或者更重要的是,通过重新定义方法或参数来覆盖。

Since the dict Object in Python allows for key/value name pairs, this enables FileInfo to have access to that same mechanism. 由于Python中的dict对象允许键/值名称对,因此这使得FileInfo可以访问相同的机制。

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. 您可以为自己的特殊目的覆盖__init____init__ __getitem____setitem__方法以扩展字典的用法。

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. 阅读Dive into Python文本中的下一部分:我们使用这种继承来处理文件信息,就像我们使用普通字典一样。

# 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. fileinfo类的设计方式是在其构造函数中接收文件名,然后让用户获取文件信息,就像从普通字典中获取值一样。

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: 您可以定义特殊的__setitem__函数,该函数对密钥名称敏感:

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: 为此,您继承了一个__getitem__函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM