[問題] 建立dictionary的子類別
小弟剛接觸python3,想嘗試做出一個可以相加的字典
將d和dd設成
d = additivedict(b=[1, 11], c=[2])
dd = additivedict(b=[111], d=[3], e=[4])
目標是讓d+dd變成
{'b':[1,11,111], 'c':[2], 'd':[3], 'd':[4]}
以下是我寫的程式
from collections import defaultdict
##import copy
class additivedict(defaultdict):
def __init__(self, **kwargs):
super().__init__(list)
if kwargs:
super().update(kwargs)
def __add__(self, other):
__sum = self ##這裡改用__sum = copy.copy(self)
for k, v in other.items():
__sum[k] += v
return __sum
if __name__ == '__main__':
d = additivedict()
dd = additivedict()
d['b'] += [1]
d['b'] += [11]
d['c'] += [2]
dd['b'] += [111]
dd['d'] += [3]
dd['e'] += [4]
這段程式是可以執行的,結果似乎也正確,但是執行d+dd後會將d的內容改變
因此我在中間有##的那行改成__sum = copy.copy(self)
程式就不能運作了,想請教問題出在哪裡,先謝謝各位了
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 180.177.108.159
※ 編輯: robert780612 來自: 180.177.108.159 (10/22 02:39)
※ 編輯: robert780612 來自: 180.177.108.159 (10/22 02:39)
→
10/22 14:11, , 1F
10/22 14:11, 1F
→
10/22 15:44, , 2F
10/22 15:44, 2F
→
10/22 15:45, , 3F
10/22 15:45, 3F
→
10/25 02:36, , 4F
10/25 02:36, 4F
Python 近期熱門文章
PTT數位生活區 即時熱門文章