官术网_书友最值得收藏!

The defaultdict class

As an example of why that's interesting, consider this-Python's standard library contains a data structure class called defaultdict, which is like a dictionary except, when we try to look up a key that isn't already in the dictionary. It creates a new value and adds it to the dictionary, before returning it to the code that tried the lookup, as shown here:

How does the defaultdict class know how to create the default value?

The defaultdict class knows because we gave it class as a parameter when we created the defaultdict class. Thus, if we want a dictionary of list, we can give the defaultdict class the list class, as its how to make a default parameter. As an aside, defaultdict can also work with a function, as its how to make a default parameter.

The defaultdict class actually doesn't care what that parameter is, as long as the object we passed can create a new object whenever the defaultdict class needs a new default. This is an example of the duck typing we mentioned in the previous section. It doesn't matter whether the parameter is a function, a class, or anything else, so long as it behaves properly. If it doesn't behave properly, we'll be told what went wrong and where.

主站蜘蛛池模板: 海口市| 周口市| 喜德县| 南投市| 云霄县| 东乡族自治县| 新营市| 芜湖市| 四平市| 阿拉善左旗| 吴江市| 天气| 乌什县| 驻马店市| 志丹县| 忻州市| 松阳县| 嘉峪关市| 阿巴嘎旗| 宜兰市| 高碑店市| 南京市| 许昌市| 禹州市| 贵定县| 云安县| 枞阳县| 新绛县| 湾仔区| 墨竹工卡县| 崇礼县| 昌吉市| 钟祥市| 启东市| 双流县| 鄂州市| 金坛市| 佛冈县| 鞍山市| 南陵县| 綦江县|