'''
自己定义一个字典,完成字典相加的功能与相减的功能,
相加:求并集[若key出现重复就覆盖]
相减:求交集
'''
class Dict(dict):
def __add__(self, other):
dict1=Dict(self.copy())
dict1.update(other)
print(type(dict1))
# for k,v in other.items():
# dict1[k]=v
return dict1
def __sub__(self, other):
dict1=Dict(self.copy())
print(type(self))
print(type(dict1))
for k in self:
if k not in other:
del dict1[k]
return dict1
if __name__ == '__main__':
d1=Dict({1:'a',2:'a'})
d2=Dict({2:'a'})
d3=Dict({3:'a'})
# print(d1+d2+d3)
print(d1-d2)
python如何让字典实现加减功能
最新推荐文章于 2024-04-28 21:22:27 发布