先上代码 #类SingleList class SingleList: def __init__(self, initialList = None): '''Initialized SingleList instance''' self.__list = [] if initialList: for value in initialList: if value not in self.__list: self.__list.append(value) def __str__(self): '''Overlaoded string representation''' tempString = "" i = 0 for i in range(len(self)): tempString += "%12d" % self.__list[i] if((i+1) % 4 == 0): tempString += "/n" if i % 4 != 0: tempString += "/n"; return tempString def __len__(self): '''Overload length of the list''' return len(self.__list) def __getitem__(self, index): '''Overload sequence element access''' return self.__list[index] def __setitem__(self, index, value): '''Overload sequence element set''' if value in self.__list: raise ValureError self.__list[index] = value def __eq__(self, other): '''Overload equality operator''' if len(self) != len(other): return 0 for i in range(len(self)): if self.__list[i] != other.__list[i]: return 0 return 1 def __ne__(self, other): '''Overload != and <> operators''' return not(self == other) #类SingleList的驱动程序 def readInput(): '''read input''' size = int(input("List size:")) readList = [] for i in range(size): readList.append(int(input())) return readList list1 = SingleList(readInput()) list2 = SingleList(readInput()) print("length of list1 %d" % (len(list1))) print("length of list2 %d" % (len(list2))) if list1 == list2: print("equal") if list1 != list2: print("Not equal") print(str(list1)) print("the 1st element in list1 is:", list1[0]) list1[0] = 100 print("after assign, the 1st element in list1 is:", list1[0]) 越来越喜欢Python了,上面这个类重载了一些运算符比如==, !=, len(), str()等等,学过C++对这学起来相当的轻松。但是还是刚入门,离精通还是远着的,继续加油加油啊。