Python面向对象进阶示例--自定义数据类型

需求:

基于授权定制自己的列表类型,要求定制的自己的__init__方法,
定制自己的append:只能向列表加入字符串类型的值
定制显示列表中间那个值的属性(提示:property)
其余方法都使用list默认的(提示:__getattr__加反射)

 1 class List:
 2     def __init__(self,value):
 3         self.x=list(value)
 4     def append(self,value):
 5         if not isinstance(value,str):
 6             raise TypeError('append到列表的内的元素必须是str类型')
 7         self.x.append(value)
 8     def insert(self,index,value):
 9         self.x.insert(index,value)
10     def __getattr__(self, item):
11         return getattr(self.x,item)
12 
13     @property
14     def type(self):
15         print(self.x)
16         t=int(len(self.x)/2)
17         print(self.x[t],type(self.x[t]))
18 
19 
20 l=List([1,2,3])
21 l.append("egon")
22 l.append('hello')
23 l.append('alex')
24 l.insert(7,5)
25 l.pop()
26 l.type

 

posted @ 2017-04-24 16:35  f_manito  阅读(1987)  评论(0编辑  收藏  举报