- Daniel Arbuckle's Mastering Python
- Daniel Arbuckle
- 215字
- 2021-07-02 21:09:32
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.
- Advanced Quantitative Finance with C++
- C# 2012程序設(shè)計實踐教程 (清華電腦學(xué)堂)
- Linux核心技術(shù)從小白到大牛
- 你必須知道的204個Visual C++開發(fā)問題
- The HTML and CSS Workshop
- 大模型RAG實戰(zhàn):RAG原理、應(yīng)用與系統(tǒng)構(gòu)建
- Hands-On Reinforcement Learning with Python
- 學(xué)習(xí)正則表達(dá)式
- 從Java到Web程序設(shè)計教程
- Webpack實戰(zhàn):入門、進(jìn)階與調(diào)優(yōu)
- PyQt編程快速上手
- CodeIgniter Web Application Blueprints
- 邊玩邊學(xué)Scratch3.0少兒趣味編程
- 實戰(zhàn)Python網(wǎng)絡(luò)爬蟲
- 你真的會寫代碼嗎