码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-04-24 17:23:21      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:div   反射   value   not   return   class   pre   使用   print   

需求:

基于授权定制自己的列表类型,要求定制的自己的__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

 

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

标签:div   反射   value   not   return   class   pre   使用   print   

原文地址:http://www.cnblogs.com/baomanji/p/6757582.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!