[英]How do I build a __add__ method in a specific class in python?
我定義了一個名為DictList
的類。 DictList
類表示字典列表,其中一些鍵出現在一個以上的字典中,它具有一個參數:它匹配一個或多個參數(必須為字典)。
class DictList:
def __init__(self,*args):
self.n = args
喜歡 :
A = DictList({'a':1, 'b':2, 'c':3}, {'c':5, 'd':7, 'e':16}, {'e':25, 'f':29)
現在,我想在此類中定義一個add方法。 它將把兩個DictList加在一起,或者增加一個DictList和一個字典。
例:
>>> A1 = DictList(dict(a=1,b=2), dict(b=12,c=13))
>>> A2 = DictList(dict(a='hi',b='hello'), dict(b='good',c='nice'))
>>> A1+A2
DictList({'a': 1, 'b': 2}, {'b': 12, 'c': 13}, {'a': 'hi', 'b': 'hello'}, {'b': 'good', 'c': 'nice'})
>>> A2 + A1
DictList( {'a': 'hi', 'b': 'hello'}, {'b': good', 'c': 'nice'},{'a': 1, 'b': 2}, {'b': 12, 'c': 13})
我的想法是用字典列表創建一個新的DictList,該字典列表包含兩個DictList中的所有字典或一個DictList和一個字典。
def __add__(self,new):
if type(new) == DictList:
print(DictList( all dicts from self and new ))
if type(new) == dict:
print(DictList(all dicts from self and new))
但是我不知道如何在兩個DictList中獲取每個字典並將其全部放入新的DictList中,該怎么辦?
返回帶有聯接的self.n
參數列表的新DictList
。 如果您也想添加常規詞典,請檢查實例的類型。 您可能需要定義__radd__
來處理dict + DictList
而不是僅DictList + dict
。
class DictList:
def __init__(self,*args):
self.n = args
def __add__(self,new):
L = list(self.n)
if isinstance(new,DictList):
L.extend(new.n)
elif isinstance(new,dict):
L.append(new)
else:
raise TypeError('Must be instance of DictList or dict')
return DictList(*L)
def __radd__(self,new):
return self.__add__(new)
def __repr__(self):
return 'DictList'+repr(self.n)
演示:
>>> d = DictList(dict(a=1,b=2,c=3),dict(a=2,b=3,e=4))
>>> e = DictList(dict(a=4,c=2,e=3))
>>> d+e
DictList({'b': 2, 'c': 3, 'a': 1}, {'b': 3, 'a': 2, 'e': 4}, {'c': 2, 'a': 4, 'e': 3})
>>> d+dict(x=1,y=2)
DictList({'b': 2, 'c': 3, 'a': 1}, {'b': 3, 'a': 2, 'e': 4}, {'x': 1, 'y': 2})
>>> dict(x=1,y=2)+d
DictList({'b': 2, 'c': 3, 'a': 1}, {'b': 3, 'a': 2, 'e': 4}, {'x': 1, 'y': 2})
>>> d+5
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Users\metolone\Desktop\x.py", line 12, in __add__
raise TypeError('Must be instance of DictList or dict')
TypeError: Must be instance of DictList or dict
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.