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

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.

主站蜘蛛池模板: 武穴市| 天峻县| 山丹县| 平陆县| 阿拉尔市| 北流市| 永春县| 哈巴河县| 宁陵县| 大悟县| 元氏县| 江口县| 通化县| 新建县| 龙泉市| 儋州市| 哈巴河县| 凤台县| 定陶县| 娄底市| 黄大仙区| 阜宁县| 淳安县| 社旗县| 于都县| 临沭县| 临颍县| 宣恩县| 隆回县| 美姑县| 吴忠市| 社旗县| 铜山县| 南宫市| 行唐县| 南部县| 芮城县| 叙永县| 云和县| 广宗县| 濮阳市|