我们可以使用多重继承来简单地创建OrderedCounter:
We can create an OrderedCounter trivially by using multiple inheritance:
>>> from collections import Counter, OrderedDict >>> class OrderedCounter(Counter, OrderedDict): ... pass ... >>> OrderedCounter('Mississippi').items() [('M', 1), ('i', 4), ('s', 4), ('p', 2)]如果我错了,请纠正我,但这在很大程度上取决于以下事实: Counter使用super :
Correct me if I'm wrong, but this crucially relies on the fact that Counter uses super:
class Counter(dict): def __init__(*args, **kwds): ... super(Counter, self).__init__() ...就是说,魔术是有效的,因为
That is, the magic trick works because
>>> OrderedCounter.__mro__ (__main__.OrderedCounter, collections.Counter, collections.OrderedDict, dict, object)super调用必须根据 mro ,自定义类将OrderedDict用作存储后端.
The super call must delegate according to 'siblings before parents' rule of the mro, whence the custom class uses an OrderedDict as the storage backend.
但是,最近一位同事指出,OrderedDict 不使用超级:
However a colleague recently pointed out, to my surprise, that OrderedDict doesn't use super:
def __setitem__(self, key, value, dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link): ... # <some weird stuff to maintain the ordering here> dict_setitem(self, key, value)起初我以为可能是因为OrderedDict首先出现,而Raymond后来也没有去更改它,但似乎super早于OrderedDict.
At first I thought it could be because OrderedDict came first and Raymond didn't bother to change it later, but it seems that super predates OrderedDict.
为什么OrderedDict显式调用dict.__setitem__?
Why does OrderedDict call dict.__setitem__ explicitly?
为什么它需要成为一个怪人?在钻石继承情况下使用OrderedDict时,这是否会引起麻烦,因为它直接传递给父类,而不是委托给mro中的下一行?
And why does it need to be a kwarg? Doesn't this cause trouble when using OrderedDict in diamond inheritance situations, since it passes directly to the parent class instead of delegating to the next in line in the mro?
推荐答案这是微优化.查找dict_setitem自变量比查找dict.__setitem__或super().__setitem__稍快.
It's a microoptimization. Looking up a dict_setitem argument is slightly faster than looking up dict.__setitem__ or super().__setitem__.
如果您有另一个覆盖__setitem__的类,则这可能会导致多重继承问题,但是OrderedDict并不是为那种覆盖钻石结构的方法而设计的.为了使OrderedDict支持这一点,必须非常谨慎地保证在排序信息与dict结构不一致的情况下,如果另一个类的方法尝试为OrderedDict编制索引,可能会看到什么.这样的保证实在太麻烦了.
This might cause problems with multiple inheritance if you have another class that overrides __setitem__, but OrderedDict isn't designed for that kind of diamond-structured method overriding anyway. For OrderedDict to support that, it'd have to make very careful guarantees about what another class's methods might see if they try to index the OrderedDict while the ordering information is inconsistent with the dict structure. Such guarantees would be way too messy to make.
更多推荐
为什么OrderedDict不使用super?
发布评论