簡體   English   中英

從OrderedDict和defaultdict繼承子類

[英]subclassing from OrderedDict and defaultdict

Raymond Hettinger 展示了一種非常酷的方式來組合集合類:

from collections import Counter, OrderedDict
class OrderedCounter(Counter, OrderedDict):
  pass
# if pickle support is desired, see original post

我想為OrderedDict和defaultdict做類似的事情。 但是,當然,defaultdict具有不同的__init__簽名,因此需要額外的工作。 解決這個問題最簡潔的方法是什么? 我使用Python 3.3。

我在這里找到了一個很好的解決方案: https//stackoverflow.com/a/4127426/336527 ,但我想可能從defaultdict中獲得可能會使這更簡單?

在鏈接到的答案中繼承OrderedDict是最簡單的方法。 實現有序存儲比從工廠函數獲取默認值要多得多。

你需要為defaultdict實現的是一些自定義__init__邏輯和非常簡單的__missing__

如果你改為從defaultdict繼承,你必須委托或重新實現至少__setitem__ __iter____iter__ __delitem____iter__來重現順序操作。 您仍然需要在__init__進行設置工作,盡管您可能可以繼承或根據您的需要省略其他一些方法。

查看原始配方其他任何與其他Stack Overflow問題相關聯的問題 ,了解其中包含的內容。

我找到了一種方法來對它們進行子類化,但不確定是否存在錯誤:

class OrderedDefaultDict(defaultdict, OrderedDict):
    def __init__(self, default, *args, **kwargs):
        defaultdict.__init__(self, default)
        OrderedDict.__init__(self, *args, **kwargs)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM