为什么实例变量在Python中表现得像一个类变量? [英] Why is instance variable behaving like a class variable in Python?

查看:133
本文介绍了为什么实例变量在Python中表现得像一个类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Python中的最少惊讶:可变默认参数

我有以下代码:

class Node(object):
    def __init__(self, value = 0, children = {}):
        self.val = value
        self.children = children

    def setChildValue(self, index, childValue):
        self.children[index] = Node(childValue)

n = Node()
n.setChildValue(0,10)
print n.children
n2 = Node()
print n2.children

并打印:

{0: <__main__.Node object at 0x10586de90>}
{0: <__main__.Node object at 0x10586de90>}

所以我的问题是,为什么n2中定义了孩子?

So my question is, why is children defined in n2? Children is an instance variable and yet it's acting like a class variable.

感谢

推荐答案

您在每个实例上为 children 分配相同的字典。

You're assigning the same dictionary to children on every instance.

这篇关于为什么实例变量在Python中表现得像一个类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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