以下代码不起作用。
def set_view_counts(self):
"""
Initializes the view counts for all of the Concept objects in the ConceptModel. See Concept for a
description of why this parameter is optional.
"""
for node in self.nodes():
p = PageviewsClient().article_views("en.wikipedia", [node.concept.replace(' ', '_')])
p = [p[key][node.concept.replace(' ', '_')] for key in p.keys()]
p = int(sum([daily_view_count for daily_view_count in p if daily_view_count])/len(p))
node.properties['view_count'] = p
当我查看node.properties
词典的内容时,我发现4560, 4560, 4560, 4560
。
以下代码可以。
def set_view_counts(self):
"""
Initializes the view counts for all of the Concept objects in the ConceptModel. See Concept for a
description of why this parameter is optional.
"""
for node in self.nodes():
p = PageviewsClient().article_views("en.wikipedia", [node.concept.replace(' ', '_')])
p = [p[key][node.concept.replace(' ', '_')] for key in p.keys()]
p = int(sum([daily_view_count for daily_view_count in p if daily_view_count])/len(p))
node.properties = p
当我查看属性时,我找到11252, 7367, 3337, 4560
。
这里发生了什么?
答案 0 :(得分:1)
我们需要看到更多你的代码,但是我在你的函数中添加了一些内容,猜测你可以编写什么来重现你的bug:
_
有了这个,我得到:
class Node:
def __init__(self, props={}):
self.properties = props
class G:
def __init__(self):
self.n = [Node(), Node(), Node(), Node()]
def nodes(self):
return self.n
def set_view_counts(self):
p = 0
for node in self.nodes():
node.properties['view_count'] = p
p = p + 1
def __repr__(self):
r = ''
for node in self.nodes():
r += node.properties.__repr__()
return r
g = G()
g.set_view_counts()
print g
这是因为{'view_count': 3}{'view_count': 3}{'view_count': 3}{'view_count': 3}
中props
参数的默认值。所有Node.__init__
共享相同的dict
(用作默认值的Nodes
。通过删除默认值来解决此问题。