[英]Assigning items to a dictionary of an object
以下代码不起作用。
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
。
这里发生了什么?
我们将需要看更多的代码,但是我在您的函数周围放了一些内容,猜测您可以编写些什么来重现您的错误:
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}
这是因为Node.__init__
props
参数的默认值。 所有Nodes
共享相同的dict
(用作默认值)。 通过删除默认值来解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.