【基礎】練習冊3-Python3_自定義列表的運算

代碼如下:

#自定義列表的運算

#DataList類以數(shù)值列表為屬性,重載了多種運算方法

class DataList:

? ? #所有的元素都必須是數(shù)字

? ? def __isNumber(self,n):

? ? ? ? if not isinstance(n,(int,float,complex)):

? ? ? ? ? ? #isinstance()函數(shù),判斷一個對象是否是已知類型,類似type()

? ? ? ? ? ? return False

? ? ? ? return True

? ? def __init__(self,*args):

? ? ? ? if not args:

? ? ? ? ? ? self.__data=[]

? ? ? ? else:

? ? ? ? ? ? for arg in args:

? ? ? ? ? ? ? ? if not self.__isNumber(arg):

? ? ? ? ? ? ? ? ? ? print("All elements must be numbers")

? ? ? ? ? ? ? ? return

? ? ? ? ? ? self.__data=list(args)

? ? #重載運算符+:列表中每個元素都與數(shù)字n相加,或兩個列表相加,返回新列表

? ? def __add__(self,n):

? ? ? ? temp=DataList()

? ? ? ? if self.__isNumber(n):

? ? ? ? ? ? temp.__data=[item+n for item in self.__data]

? ? ? ? ? ? return temp

? ? ? ? elif isinstance(n,DataList):

? ? ? ? ? ? temp.__data=[i+j for i,j in zip(self.__data,n.__data)]

? ? ? ? ? ? return temp

? ? ? ? else:

? ? ? ? ? ? print("Not supported")

? ? #重載運算符-:列表中每個元素都與數(shù)字n相減,返回新列表

? ? def __sub__(self,n):

? ? ? ? if not self.__isNumber(n):

? ? ? ? ? ? print('- operating with {},Datatype Error',format(type(n)))

? ? ? ? ? ? return

? ? ? ? temp = DataList()

? ? ? ? temp.__data=[item-n for iterm in self.__data]

? ? ? ? return temp

? ? #重載運算符*:列表中每個元素都與數(shù)字n相乘,返回新列表

? ? def __mul__(self,n):

? ? ? ? if not self.__isNumber(n):

? ? ? ? ? ? print('* operating with {},Datatype Error',format(type(n)))

? ? ? ? ? ? return

? ? ? ? temp = DataList()

? ? ? ? temp.__data=[item*n for iterm in self.__data]

? ? ? ? return temp

? ? #重載運算符/:列表中每個元素都與n相除,返回新列表

? ? def __truediv__(self,n):

? ? ? ? if not self.__isNumber(n):

? ? ? ? ? ? print('/ operating with {},Datatype Error',format(type(n)))

? ? ? ? ? ? return

? ? ? ? temp = DataList()

? ? ? ? temp.__data=[item/n for iterm in self.__data]

? ? ? ? return temp

? ? #重載運算符%:列表中每個元素與n求余數(shù),返回新列表

? ? def __mod__(self,n):

? ? ? ? if not self.__isNumber(n):

? ? ? ? ? ? print('% operating with {},Datatype Error',format(type(n)))

? ? ? ? ? ? return

? ? ? ? temp = DataList()

? ? ? ? temp.__data=[item%n for iterm in self.__data]

? ? ? ? return temp

? ? def __len__(self):

? ? ? return? len(self.__data)

? ? #直接使用該類對象作為表達式來查看對象的值

? ? def __repr__(self):

? ? ? ? return repr(self.__data)

? ? #追加元素

? ? def append(self,value):

? ? ? ? if not self.__isNumber(n):

? ? ? ? ? ? print(' Only number can be appended.')

? ? ? ? ? ? return

? ? ? ? self.__data.append(value)

? ? #獲取指定下表的元素值支持使用列表或元組指定多個下標

? ? def __getitem__(self,index):

? ? ? ? length=len(self.__data)

? ? ? ? #如果指定單個整數(shù)作為下標,則直接返回元素值

? ? ? ? if isinstance(index,int) and 0<=index<length:

? ? ? ? ? ? return self.__data[index]

? ? ? ? elif isinstance(index,(list,tuple)):

? ? ? ? ? ? if i in index:

? ? ? ? ? ? ? ? if not (isinstance(i,int) and 0<=i<=length):

? ? ? ? ? ? ? ? ? ? return 'index error'

? ? ? ? ? ? ? ? result=[]

? ? ? ? ? ? ? ? for item in index:

? ? ? ? ? ? ? ? ? ? result.append(self.__data[item])

? ? ? ? ? ? ? ? return result

? ? ? ? else:

? ? ? ? ? ? return 'index error'

? ? #修改元素值,支持使用列表或元組指定多個下標,同時修改多個元素值

? ? def __setitem__(self,index,value):

? ? ? ? length=len(self.__data)

? ? ? ? #如果下表合法,則直接修改元素值

? ? ? ? if isinstance(index,int) and 0<=index<length:

? ? ? ? ? ? self.__data[index]=value

? ? ? ? #支持使用列表或元組指定多個下標

? ? ? ? elif isinstance(index,(list,tuple)):

? ? ? ? ? ? for i in index:

? ? ? ? ? ? ? ? if not (isinstance(i,int) and 0<=i<length):

? ? ? ? ? ? ? ? ? ? raise Exception('index error')

? ? ? ? ? ? #如果下標和給的值都是列表或元組,并且個數(shù)一樣,則分別為多個下標的元素修改值

? ? ? ? ? ? if isinstance(value,(list,tuple)):

? ? ? ? ? ? ? ? if len(index)==len(value):

? ? ? ? ? ? ? ? ? ? for i,v in enumerate(index):

? ? ? ? ? ? ? ? ? ? ? ? self.__data[v]=value[i]

? ? ? ? ? ? ? ? else:

? ? ? ? ? ? ? ? ? ? raise Exception('values and index must be of the same length')

? ? ? ? ? ? elif isinstance(value,(int,float,complex)):

? ? ? ? ? ? ? ? for i in index:

? ? ? ? ? ? ? ? ? ? self.__data[i]=value

? ? ? ? ? ? else:

? ? ? ? ? ? ? ? raise Exception('value error')

? ? ? ? else:

? ? ? ? ? ? raise Exception('value error')

? ? #支持成員測試運算符in,測試列表中是否包含某個元素

? ? def __contain__(self,value):

? ? ? ? if value in self.__data:

? ? ? ? ? ? return True

? ? ? ? return False

? ? #重載運算符==,測試兩個列表是否相等

? ? def __eq__(self,value):

? ? ? ? if not isinstance(value,DataList):

? ? ? ? ? ? print(value,'must be an instance of DataList.')

? ? ? ? ? ? return False

? ? ? ? if self.__data==value.__data:

? ? ? ? ? ? return True

? ? ? ? return False

? ? #重載運算符<,比較兩個列表大小

? ? def __lt__(self,value):

? ? ? ? if not isinstance(value,DataList):

? ? ? ? ? ? print(v,'must be an instance of DataList.')

? ? ? ? ? ? return False

? ? ? ? if self.__data < value.__data:

? ? ? ? ? ? return True

? ? ? ? return False

# 主控程序

if __name__=='__main__':

? ? x=DataList(1,3,5,7,9)

? ? y=DataList(-2,-4,-8)

? ? print(x)

? ? print("x+y=",x+y)

? ? print("x==y",x==y)

? ? print("x+2=",x+2)

? ? print("x%2=",x%2)

? ? print("5 in x=",5 in x)

? ? print("x<y=",x<y)

? ? x[4]=['a','b','c']

? ? print(x)

? ? x=[2,4,1]=True

? ? print(x)

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容