Why is instance variable behaving like a class variable in Python? [duplicate]

守給你的承諾、 提交于 2019-11-28 08:50:01

问题


Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

I have the following code:

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

And it prints:

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

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

Thanks


回答1:


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




回答2:


When you define the function __init__ you give it a dictionary as a default argument. That dictionary is created once (when you define the function) and then used every time __init__ is called.

More information: http://effbot.org/zone/default-values.htm




回答3:


As indicated in Martijn's comment and kindall's answer, you are running into the mutable default argument behavior which bites most Python developers at some point, here is how you can modify Node.__init__() so that it works the way you expect:

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


来源:https://stackoverflow.com/questions/13144433/why-is-instance-variable-behaving-like-a-class-variable-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!