collections.Counter 和collections.defaultdict 都是继承自dict。那么它们之间导致不相似输出(“类”和“类型”)的区别是什么?
import collections
print str(collections.Counter)
print str(collections.defaultdict)
输出:
<class 'collections.Counter'>
<type 'collections.defaultdict'>
最佳答案
恐怕你在这里的回答会归结为一些相当无聊的东西: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 编写的内置扩展。
如果对 deque
(也是 C)或用 Python 编写的 collections
中的其他类进行字符串化处理,您会发现同样的行为:
>>> from collections import deque
>>> str(deque)
"<type 'collections.deque'>"
>>> from collections import OrderedDict
>>> str(OrderedDict)
"<class 'collections.OrderedDict'>"*
关于Python 2.7 : applying str to collections. 计数器和 collections.defaultdict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35805550/