返回顶部

通过包装定制自己的数据类型

需求:通过继承来构建自己的数据类型:(例子:列表中只能添加字符串)

 1 class List(list):
 2     def append(self,object):
 3         if type(object) == str:
 4             # self.append(object) #不行,构成递归
 5             super().append(object)#使用父类中的方法
 6             #父类中的append 和 子类中的append 是不同的,下面证明
 7             print(id(super().append))
 8             print(id(self.append))
 9         else:
10             print("只能添加字符串")
11 
12 if __name__ =="__main__":
13     list = List()
14     list.append("tom")
15     list.append(123)
16     print(list)
17 '''
18 输出:
19 2144665322048
20 2144663681800
21 只能添加字符串
22 ['tom']
23 '''

 

包装的扩展:

下面通过包装实现 权限管理,给增加时间,过滤敏感词

 1 import time
 2 class Open:
 3     def __init__(self,fileName,mode = 'r',encoding = 'utf8'):
 4         self.file=open(fileName,mode,encoding=encoding) #得到一个对象
 5         self.mode = mode
 6         self.encoding = encoding
 7     def write(self,text):
 8         add = time.strftime("%Y-%m-%d %X") # %X 代表时间
 9         if "中国" in text:
10             print("!!!含有敏感词,请检查!")
11         else:
12             self.file.write("{} {}".format(add,text))
13     def __getattr__(self, item):
14         print("没有{}这个属性".format(item))
15 
16 if __name__ =="__main__":
17     f = Open("d:/test.txt",'w')
18     f.write("cpu负载过高\n")
19     f.write("内存剩余不足\n")
20     f.write("硬盘剩余不足\n")
21     f.write("中国\n")
22     # f.read()  #没有read这个属性
23 
24     '''
25         输出:
26         !!!含有敏感词,请检查!
27 
28         文件中的内容:
29         2019-08-06 16:18:28 cpu负载过高
30         2019-08-06 16:18:28 内存剩余不足
31         2019-08-06 16:18:28 硬盘剩余不足
32     '''
posted @ 2019-08-06 15:54  Zcb0812  阅读(127)  评论(0编辑  收藏  举报