python item系列
1 class Foo:
2 """
3 把对象属性模拟成dict形式
4 访问:dict[key] = value
5
6 """
7 def __init__(self,name):
8 self.name = name
9 def __getitem__(self, item):
10 return self.__dict__[item]
11 def __setitem__(self, key, value):
12 setattr(self,key,value)
13 # self.__dict__[key] = value
14 def __delitem__(self, key):
15 # return delattr(self,key)
16 return self.__dict__.pop(key)
17
18
19
20 f1 = Foo('biter')
21 print(f1['name'])
22 f1['age'] = 10
23 f1['addr'] = 'china'
24 print(f1['age'])
25 print(f1.__dict__)
26 del f1['age']
27 print(f1.__dict__)