你好,我有这两个班
class BaseCounter(object):
def __init__(self):
print ("BaseCounter init = ")
self._counter = 0
def increment(self, count=1):
self._counter += count
def items(self):
return self._counter
class DictCounter(object):
def __init__(self, dict_class):
self._counter = defaultdict(lambda: dict_class)
def increment(self, key, value, *args, **kwargs):
print (key, value, args, kwargs)
self._counter[key].increment(value, *args, **kwargs)
def items(self):
result = []
for key, counter in self._counter.items():
result.append((key, counter.items()))
return result
我正试图创造这样的东西:
^{pr2}$从而导致
10 1 2 12
10 1 3 12
10 2 2 12
10 2 3 12
但我早就预料到了
10 1 2 6
10 1 3 3
10 2 2 3
它应该模拟,这是正确的工作
defaultdict(defaultdict(defaultdict(int))) "with counter at the end"
但我对这种行为感到困惑(我认为浅拷贝或参考文献会有问题)
有什么想法吗?在
正如马蒂恩·皮特斯所说。问题是为每个新键引用同一个对象(dict_类)。所以不是这样:
这样做:
^{pr2}${我想再描述一下。在
相关问题 更多 >
编程相关推荐