码迷,mamicode.com
首页 > 其他好文 > 详细

item系列

时间:2018-06-07 14:19:06      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:item   foo   color   print   att   --   int   TE   引号   

 1 class Foo:
 2     def __getitem__(self, item):
 3         print(-------->__getitem__)
 4         return self.__dict__[item]
 5     def __setitem__(self, key, value):
 6         print(-------->__setitem__)
 7         self.__dict__[key] = value
 8     def __delitem__(self, key):
 9         print(-------->__delitem__)
10         self.__dict__.pop(key)
11 
12 f1 = Foo()
13 f1.name = stt     #f1.name 用点的方法只会触发__xxxattr__的属性,要出发item需要用a["b"]的方式
14 print(f1.__dict__)  #{‘name‘: ‘stt‘}
15 
16 # print(f1[‘name‘])              #-------->__getitem__
17 ## setitem
18 print(f1.__dict__)    #{}
19 f1[name] = stt    #-------->__setitem__记得[""]里加引号
20 print(f1.__dict__)    #{‘name‘: ‘stt‘}
21 ## getitem
22 f1[name]            #-------->__getitem__
23 print(f1[name])   #-------->__getitem__  \n   stt
24 ## delitem
25 print(f1.__dict__)     #{‘name‘: ‘stt‘}
26 del f1[name]         #-------->__delitem__
27 print(f1.__dict__)     #{}

 

item系列

标签:item   foo   color   print   att   --   int   TE   引号   

原文地址:https://www.cnblogs.com/humanskin/p/9149690.html

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