2015-12-30 306 views
0

以下代碼不起作用。將項目分配給對象字典

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

可能只是我或其原因可能很簡單,考慮到你將p存儲在屬性['view_count']而不是屬性? – Torxed

+0

相關將我帶到http://stackoverflow.com/questions/38987/how-can-i-merge-two-python-dictionaries-in-a-single-expression?rq=1,它解決了這個問題。但我仍然想明白這裏的問題是什麼;我可以說這個問題是關於「自我」是一個臨時對象的問題,但我不能爲了我的生活而看到爲什麼。 –

+0

如果這是一個「自我」相關的問題,將需要你所有的代碼,看看你在其他地方如何使用self.nodes – Torxed

回答

1

我們需要看到更多的代碼,但是我把一些肉在你的功能,猜測你可以寫重現你的錯誤:

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(用作默認值的那個)。通過刪除默認值來解決這個問題。

+0

啊!這讓我每一次! http://docs.python-guide.org/zh/latest/writing/gotchas/#mutable-default-arguments 謝謝。 –