2014-04-02 95 views
1

在下面的代碼中,我有一個包含兩個字段的對象:一個字典和一個聚合器。聚合器的目標是在O(1)時間內給出字典值的總和。 我認爲使用特性,以控制進入領域,但字典setter方法永遠不會被調用:對python對象中數據字段的訪問控制

class C: 
    def __init__(self): 
     self._p = dict() 
     self._sum_of_p_values = 0 

    def get_p(self): 
     print('getting p') 
     return self._p 
    def set_p(self, v): 
     print('setting p') 
     self._p = v 
     print('updating the sum') 
     self._sum_of_p_values = sum(self._p.values()) 
    def get_sum_of_values(self): 
     return self._sum_of_p_values 
    p = property(get_p, set_p, None, None) 
    sum_of_values = property(get_sum_of_values, None, None, None) #read-only property 

c = C() 
c.p['a'] = 1 #value created, expect to update the aggregator 
c.p['b'] = 2.14 #value created, expect to update the aggregator 
# I want c.sum_of_values to be 3.14 
print(c.sum_of_values) 

這是上面代碼的輸出:

getting p 
getting p 
0 

什麼實現我的目標的最佳途徑?

回答

0

您直接設置屬性而不是使用setter方法。試試這個:

class C: 
    def __init__(self): 
     self._p = dict() 
     self._sum_of_p_values = 0 

    def get_p(self): 
     print('getting p') 
     return self._p 
    def set_p(self, k, v): 
     print('setting p') 
     self._p[k] = v 
     print('updating the sum') 
     self._sum_of_p_values = sum(self._p.values()) 
    def get_sum_of_values(self): 
     return self._sum_of_p_values 
    p = property(get_p, set_p, None, None) 
    sum_of_values = property(get_sum_of_values, None, None, None) #read-only property 

c = C() 

c.set_p('a', 1) #value created, expect to update the aggregator 
c.set_p('b', 2.14) #value created, expect to update the aggregator 
# I want c.sum_of_values to be 3.14 
print(c.sum_of_values) 

如果你不想直接打電話給你的二傳手,則可以使用這種方法:

https://stackoverflow.com/a/5021107/2011147

+0

你是正確的,我不希望直接調用setter方法是不,我想保持「乾淨」的語法。否則,需要刪除'p'的屬性定義以確保不會造成混淆。 –