Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 类从封闭范围获取kwargs_Python_Dictionary_Trie - Fatal编程技术网

Python 类从封闭范围获取kwargs

Python 类从封闭范围获取kwargs,python,dictionary,trie,Python,Dictionary,Trie,Python似乎从类方法的封闭范围推断出一些Kwarg,我不知道为什么。我正在实施一个Trie: class TrieNode(object): def __init__(self, value = None, children = {}): self.children = children self.value = value def __getitem__(self, key): if key == "": return self.value

Python似乎从类方法的封闭范围推断出一些Kwarg,我不知道为什么。我正在实施一个Trie:

class TrieNode(object):
  def __init__(self, value = None, children = {}):
    self.children = children
    self.value = value

  def __getitem__(self, key):
    if key == "":
        return self.value
    return self.children[key[0]].__getitem__(key[1:])

  def __setitem__(self, key, value):
    if key == "":
        self.value = value
        return
    if key[0] not in self.children:
        self.children[key[0]] = TrieNode()
    self.children[key[0]].__setitem__(key[1:], value)
在倒数第二行,我创建了一个新的三部曲,大概是一本空的儿童词典。但是,当我检查生成的数据结构时,树中的所有三元组都使用相同的子字典。即,如果我们这样做:

>>>test = TrieNode()
>>>test["pickle"] = 5
>>>test.children.keys()
['c', 'e', 'i', 'k', 'l', 'p']
然而,测试的子项应该只包含指向新三元组的“p”。另一方面,如果我们进入代码的倒数第二行,并将其替换为:

        self.children[key[0]] = TrieNode(children = {})
然后它就如预期的那样工作了。不知何故,self.children字典被隐式传递为kwarg to Trinode(),但为什么呢?

您遇到了一个问题。将
\uuuu init\uuuu
函数更改为如下所示

def __init__(self, value=None, children=None):
    if not children:
        children = {}
子函数的默认值只在函数创建时计算一次,而您希望它在每次调用中都是一个新的dict

下面是一个使用列表的简单问题示例

>>> def f(seq=[]):
...     seq.append('x') #append one 'x' to the argument
...     print(seq) # print it
>>> f() # as expected
['x']
>>> f() # but this appends 'x' to the same list
['x', 'x']
>>> f() # again it grows
['x', 'x', 'x']
>>> f()
['x', 'x', 'x', 'x']
>>> f()
['x', 'x', 'x', 'x', 'x']

正如我链接到的答案所描述的,这最终会影响到每个python程序员。

您所经历的行为来自以下几行:

def __init__(self, value = None, children = {}):
children={}
称为。在这种情况下,默认参数在函数定义上构造一次,每次修改都会影响将来的每个函数调用(使用默认值)。 要解决此问题,应将
None
作为默认值传递(由于
None
不可更改,因此上述行为不适用):


明确地说,Python在解释时为默认值计算并分配一次内存位置;所有进一步的访问(运行时)都只是查看该内存位置。如果您使用可变对象(list,dict),这就是出现问题的地方。我喜欢
self.children=children或{}
def __init__(self, value = None, children = None):
    self.children = children if children else {}
    self.value = value