Python空字典没有通过引用传递? [英] Python empty dict not being passed by reference?

查看:51
本文介绍了Python空字典没有通过引用传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个示例代码有点奇怪,但请耐心等待...

This sample is code is a bit odd, but bear with me...

class Foo(object):
    def __init__(self, internal_dict = None):
        self._internal_dict = internal_dict or {}

        for attribute_name in self.__class__.__dict__.keys():
            attr = getattr(self.__class__, attribute_name)
            if isinstance(attr, str) and attribute_name.startswith("a"):
                # We are iterating over all string attributes of this class whos name begins with "a" 
                self._internal_dict[attribute_name] = {}
                setattr(self, attribute_name + '_nested_object', Foo(internal_dict=self._internal_dict[attribute_name]))

class FooChild(Foo):
    ax = "5"
    ay = "10"

fc = FooChild()

print fc.ax_nested_object._internal_dict # This prints {}

fc.ax_nested_object._internal_dict['123'] = 'abc'

print fc._internal_dict # This prints {'ay': {}, 'ax': {}}

我本来希望我的 {'123' = 'abc'} 已经通过第二次打印,因为字典应该已经传递到递归 __init__参考调用.但是,如果我更改这一行:

I would have expected my {'123' = 'abc'} to have gotten through to the second print because the dictionary should have been passed into the recursive __init__ call by reference. However, if I change this line:

self._internal_dict[attribute_name] = {}

为此:

self._internal_dict[attribute_name] = {'test': 1}

然后我得到以下打印:

{'test': 1}
{'ay': {'test': 1}, 'ax': {'test': 1, '123': 'abc'}}

为什么启动该字典数据会导致它通过引用正确传递?

Why does priming that dictionary data cause it to be passed properly by reference?

推荐答案

这是问题所在:

self._internal_dict = internal_dict or {}

空字典是假的,因此您将在后续递归调用中得到一个 空字典.这就是为什么将 dict 初始化为非空(真实)修复"它的原因.

An empty dict is falsy, so you will get a new empty dict on subsequent recursive calls. That's why initializing the dict to non-empty (truthy) "fixes" it.

你想要:

self._internal_dict = {} if internal_dict is None else internal_dict

这篇关于Python空字典没有通过引用传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆