1.创建list类的子类Namedlist,初始化新类,创建新对象实例johnny,检查对象类型,并使用list的一些功能来存储数据
>>> class Namedlist(list): def __init__(self,a_name): list.__init__([]) self.name=a_name >>> johnny=Namedlist("John Paul Jones") >>> type(johnny) <class '__main__.Namedlist'> >>> dir(johnny) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'name', 'pop', 'remove', 'reverse', 'sort'] >>> johnny.append("Bass Palyer") >>> johnny.extend(['Composer','Arrager','Mussical']) >>> johnny ['Bass Palyer', 'Composer', 'Arrager', 'Mussical'] >>> johnny.name 'John Paul Jones' >>> for attr in johnny: print(johnny.name + "is a" + attr +".") John Paul Jonesis aBass Palyer. John Paul Jonesis aComposer. John Paul Jonesis aArrager. John Paul Jonesis aMussical.
2. 创建Athletelist继承list类来实现vera
列表的扩展
def senitize(time_string): if '-' in time_string: splitter='-' elif ':' in time_string: splitter=':' else: return(time_string) (mins,secs)=time_string.split(splitter) return(mins+'.'+secs) class Athletelist(list): def __init__(self,a_name,a_dob=None,a_times=[]): list.__init__([]) self.name=a_name self.dob=a_dob self.extend(a_times) def top3(self): return(sorted(set([senitize(t) for t in self]))[0:3]) vera=Athletelist('VeraName') vera.append('1.31') print('Object name is:', vera.name) print(vera.name+"'s top3 is: " + str(vera.top3())) vera.extend(['2.12','3.44','3.33']) print(vera.name+"'s top3 is: " + str(vera.top3())) ========== RESTART: C:UsersericDocumentsPythonkellykelly3.py ========== Object name is: VeraName VeraName's top3 is: ['1.31'] VeraName's top3 is: ['1.31', '2.12', '3.33']