【问题标题】:Why is instance variable behaving like a class variable in Python? [duplicate]为什么实例变量表现得像 Python 中的类变量? [复制]
【发布时间】:2012-10-30 17:25:09
【问题描述】:

可能重复:
“Least Astonishment” in Python: The Mutable Default Argument

我有以下代码:

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 中定义了孩子? Children 是一个实例变量,但它的行为就像一个类变量。

谢谢

【问题讨论】:

标签: python class variables instance


【解决方案1】:

您在每个实例上都将同一个字典分配给 children

【讨论】:

    【解决方案2】:

    当你定义函数__init__ 时,你给它一个字典作为默认参数。该字典创建一次(当您定义函数时),然后在每次调用 __init__ 时使用。

    更多信息: http://effbot.org/zone/default-values.htm

    【讨论】:

      【解决方案3】:

      正如 Martijn 的评论和 kindall 的回答中所指出的,您遇到了在某些时候会困扰大多数 Python 开发人员的可变默认参数行为,您可以通过以下方式修改 Node.__init__() 使其按您期望的方式工作:

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

      【讨论】:

        猜你喜欢
        • 2017-01-02
        • 2012-12-17
        • 2013-10-10
        • 2011-02-12
        • 2012-01-31
        • 1970-01-01
        • 1970-01-01
        • 2018-01-05
        相关资源
        最近更新 更多