【问题标题】:Python default / optional VariablesPython 默认/可选变量
【发布时间】:2012-05-21 23:28:39
【问题描述】:

我正在尝试在 python 中围绕字典对象编写一个包装器对象,就像这样

class ScoredList():
    def __init__(self,dct={}):
        self.dct = dct

list = ScoredList()
list.dct.update({1,2})

list2 = ScoredList()
list.dct.update({"hello","world"})

print list1.dct, list2.dct # they are the same but should not be!

似乎我无法创建新的 ScoredList 对象,或者更确切地说,每个评分列表对象都共享相同的基础字典。这是为什么呢?

class ScoredList2():
    def __init__(self):
        self.dct = {}

ScoredList2 的上述代码运行良好。但我想知道如何在 python 中正确地重载构造函数。

【问题讨论】:

标签: python dictionary overloading


【解决方案1】:

字典是一个可变对象。在 Python 中,创建函数时会解析默认值,这意味着将相同的空字典分配给每个新对象。

要解决这个问题,只需执行以下操作:

class ScoredList():
    def __init__(self, dct=None):
        self.dct = dct if dct is not None else {}

【讨论】:

  • 那应该是dct if dct is not None else {},否则如果你传递一个空字典__init__()会创建一个新字典而不是使用你提供的字典。
  • 你也可以dct or {}。嗯,虽然可能不太清楚。
  • @F.J 我认为这是一个非常罕见的情况 - 但是是的,如果这会是一个问题,那么您的替换将是最好的。已编辑。
  • @JoelCornett 我认为这不太清楚。简短,是的,但这绝不应该是优先事项。
  • 对于您可能希望 None 成为有效参数的情况,请使用哨兵。将NO_ARGUMENT = object() 粘贴在您的班级定义之前的某个位置,然后粘贴def __init__(self, dct=NO_ARGUMENT):
猜你喜欢
  • 2016-03-12
  • 2012-03-06
  • 2011-05-13
  • 2011-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多