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

主宰稳场 提交于 2019-11-29 15:02:20

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

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

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