collections.Counter和collections.defaultdict都是从dict继承而来的。那么它们之间有什么区别导致不相似的输出('class'和'type')?
import collections
print str(collections.Counter)
print str(collections.defaultdict)
输出:
<class 'collections.Counter'>
<type 'collections.defaultdict'>
答案 0 :(得分:3)
我担心你的回答归结为一些相当无聊的事情:Counter
是用Python编写的,而defaultdict
是用C语言编写的。
此处collections.py
。请注意,您可以向下滚动并找到Counter
的标准类定义:
########################################################################
### Counter
########################################################################
class Counter(dict):
'''Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.
...
'''
但是,defaultdict
是从_collections
导入的:
from _collections import deque, defaultdict
如this answer所述,这是一个用C语言编写的内置扩展程序。
如果你是字符串ify deque
(也是C)或用Python编写的collections
中的其他类,你会注意到你会遇到同样的行为:
>>> from collections import deque
>>> str(deque)
"<type 'collections.deque'>"
>>> from collections import OrderedDict
>>> str(OrderedDict)
"<class 'collections.OrderedDict'>"*