在下面的代码中,我有一个包含两个字段的对象:字典和聚合器。聚合器的目标是在O(1)时间内给出字典值的总和。 我想使用属性来控制对字段的访问,但是dict 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, 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 :(得分: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)
如果您不想直接致电您的二传手,您可以使用以下方法: