Python 默认行为

Python defaultdict behaviour

我 运行 今天有些行为让我有点吃惊。

from collections import defaultdict
d = defaultdict(lambda: "test")

现在 d[0]returns "test" 符合预期,但 d.get(0) 实际上 returns None。这是预期的行为吗?

是的,这是预期的,documented 行为(强调原文):

Note that __missing__() is not called for any operations besides __getitem__(). This means that get() will, like normal dictionaries, return None as a default rather than using default_factory.

是的,这是预期的。除了 mydict[x] 所有其他方法与常规 dict 完全相同。来自 documentation:

Return a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.

它覆盖的方法是__missing__,进一步阐述:

This method is called by the __getitem__() method of the dict class when the requested key is not found; whatever it returns or raises is then returned or raised by __getitem__().

Note that __missing__() is not called for any operations besides __getitem__(). This means that get() will, like normal dictionaries, return None as a default rather than using default_factory.

添加了重点。