开发者

What is the relationship between '@1' and '@2'

开发者 https://www.devze.com 2022-12-15 13:30 出处:网络
class SortedDict(dict): def __new__(cls, *args, **kwargs): instance = super(SortedDict, cls).__new__(cls, *args, **kwargs)
class SortedDict(dict):
    def __new__(cls, *args, **kwargs):
            instance = super(SortedDict, cls).__new__(cls, *args, **kwargs)
            instance.keyOrder = []
            return instance
    def __setitem__(self, key, value):
            super(SortedDict, self).__setitem__(key, value)#@1
            if key not in self.keyOrder:#@2
                self.keyOrder.append(key)

why make @2,why make a li开发者_如何学编程st 'keyOrder'.

thanks


The SortedDict is "A dictionary that keeps its keys in the order in which they're inserted." (See: documentation).

Your @1 line is storing the key-value pair in the dictionary. The @2 stores the key in an internal list to maintain order.


Because this is a Sorted dict. Dictionaries normally are unsorted, so this implementation adds a keyOrder to record the order that items are added.

0

精彩评论

暂无评论...
验证码 换一张
取 消