UserDict,UserList,UserString,可继承的字典,列表,以及字符串类,可以对列表字典以及字符串内部方进行重写。
python3中这3个模块都移入到了collection库中,
#coding=utf-8
#userdict
from collections import UserDict,UserString,UserList
class MyUserDict(UserDict):
def __getitem__(self, item):
return self.data[item]*10
#return 42
def __add__(self, other):
'''实现字典相加
'''
dict1=MyUserDict(self.data)
if isinstance(other,MyUserDict):
dict1.update(other)
return dict1
class MyString(UserString):
def lower(self):
return self.data+'\n'+self.data
class MyUserList(UserList):
def __add__(self, other):
'''
返回两个列表对应处相加,如[1,2,3]+[4,,5,6]=[5,7,9]
:param other:
:return:
'''
list1=[]
for i,j in zip(self.data,other.data):
list1.append(i+j)
return list1
if __name__=='__main__':
mydict=MyUserDict(a=12)
mydict2=MyUserDict(b=120)
# print(mydict.get('a'))
print(mydict['a'])
print(mydict+mydict2) #{'a':12,'b':120}
D = {'c': 300}
print(MyUserDict(D)+mydict)
print('*******************userstring***************')
mystr=MyString('aaacc')
print(mystr.lower())
print('*******************userlist***************')
mylist1=MyUserList([1,2])
mylist2=MyUserList([3,4])
print(mylist1+mylist2) #[4,6]
网友评论