关于collections.OrderedDict初始化的问题

来源:

后沟水库

2016-09-26

class OrderedDict(dict)
    def __init__(*args, **kwds):
        '''Initialize an ordered dictionary.  The signature is the same as
        regular dictionaries, but keyword arguments are not recommended because
        their insertion order is arbitrary.

        '''
        if not args:
            raise TypeError("descriptor '__init__' of 'OrderedDict' object "
                            "needs an argument")
        self = args[0]
        args = args[1:]
        if len(args) > 1:
            raise TypeError('expected at most 1 arguments, got %d' % len(args))
        try:
            self.__root
        except AttributeError:
            self.__root = root = []                     # sentinel node
            root[:] = [root, root, None]
            self.__map = {}
        self.__update(*args, **kwds)

代码中有一个变量:__root,过于这个root[:] = [root, root, None]
该如何理解,还请老师解答一下

写回答

1回答

程序员硕

2016-09-26

切片赋值, root还是原来列表对象, 但值是[root, root, None].

这里类似与c语言中,俩个指针指向自身,

0
4
程序员硕
回复
后沟水库
不存在内存问题,因为列表中存储的是对象的引用(指针),真正的列表对象只有一个.这样写便捷一些.
2016-09-27
共4条回复

Python高效编程技巧实战

精选50个Python案例,源自实战,全面提升Python编程能力

2582 学习 · 360 问题

查看课程