为什么类中字典中的属性值不引用该类的相同属性? [英] why doesn't an attribute value in a dictionary within a class refer to the same attribute of the class?

查看:77
本文介绍了为什么类中字典中的属性值不引用该类的相同属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class test(object): 
    def __init__(self): 
        self.a = 5 
        self.d = {'alfa': self.a}

我实例化该类的一个对象,并为其分配一个新值:

I instantiate an object of the class, and assign a new value to it:

a_test = test()
a_test.a = 7

为什么a_test.d['alfa']保持5而不更改为7?

Why does a_test.d['alfa'] remain 5 and not change to 7?

推荐答案

您在调用构造函数时创建了字典.因此,字典中的值是在构造过程中设置的-它们不是通过引用传递的,而是通过值传递的.

You create the dictionary when you call the constructor. Therefore the values in the dictionary are set during construction - they aren't passed by reference, but rather by value.

字典中的值指向传入的对象的值,而不是对象本身.因此,简单地将self.a作为值并不会自动更新字典,除非self.a是可变的(例如,列表).

The values in the dictionary point to value of the object that is passed in, but not the object itself. So simply having self.a as a value doesn't automatically update the dictionary, unless self.a is mutable (eg. a list).

这篇关于为什么类中字典中的属性值不引用该类的相同属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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