这段代码如何工作?

时间:2018-02-02 04:01:31

标签: python

我无法理解" iterflattened"方法适用于我遇到的这段Python代码:

import collections
class nested_dict(collections.defaultdict):
    def __init__(self):
        collections.defaultdict.__init__(self, nested_dict)

    def iterflattened(self):
    """
    iterate through values with nested keys flattened into a tuple
    """
        for key, value in self.items():
            if isinstance(value, nested_dict):
                for keykey, value in value.iterflattened():
                    yield (key,) + keykey, value
            else:
                yield (key,), value

nd = nested_dict()
nd["mouse"]["chr1"]["+"] = 311
print(nd)

返回:

defaultdict(<class '__main__.nested_dict'>, {'mouse': defaultdict(<class '__main__.nested_dict'>, {'chr1': defaultdict(<class '__main__.nested_dict'>, {'+': 311})})})

&#34; iterflattened&#34;第一次打电话?当nd [&#34; mouse&#34;] trigers __getitem__时被调用?但是怎么样? 提前谢谢。

0 个答案:

没有答案