Python 2.7:将str应用于collections.Counter和collections.defaultdict

时间:2016-03-04 20:35:04

标签: python python-2.7

collections.Counter和collections.defaultdict都是从dict继承而来的。那么它们之间有什么区别导致不相似的输出('class'和'type')?

import collections

print str(collections.Counter)
print str(collections.defaultdict)

输出:

<class 'collections.Counter'>
<type 'collections.defaultdict'>

1 个答案:

答案 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'>"*