python学习之__getitem__,__setitem__,__delitem__
__getitem__(self,item)
__setitem__(self,key,value)
__delitem__(self,key)
class Foo:
def __getitem__(self, item):
print(‘getitem‘,item)
return self.__dict__[item]
def __setitem__(self, key, value):
print(‘setitem‘)
self.__dict__[key]=value
def __delitem__(self, key):
print(‘delitem‘)
self.__dict__.pop(key)
f1=Foo()
print(f1.__dict__)
# f1.name=‘egon‘ #---->setattr-------->f1.__dict__[‘name‘]=‘egon‘
f1[‘name‘]=‘egon‘#--->setitem--------->f1.__dict__[‘name‘]=‘egon‘
f1[‘age‘]=18
print(‘===>‘,f1.__dict__)
# del f1.name
# print(f1.__dict__)
#
# print(f1.age)
del f1[‘name‘]
print(f1.__dict__)
print(f1[‘age‘])
通过字典形式操作属性值(获取,设置,删除)触发以上三个方法。
区别:"."点的形式操作跟attr相关,"[]"中括号形式操作跟item相关