'''
__setitem__与__setarrt__
个人理解:item是与切片和索引有关的
'''
class Person:def __init__(self):self.cache = {}def __setitem__(self, key, value): #使p['name']='sz'是可行的 使p.name='sz'也是可行的self.cache[key] = valuedef __getitem__(self, item):return self.cache[item]def __delitem__(self, key):del self.cache[key]def __setattr__(self, key, value): #使p.name='sz'是可行的 但是p['name']='sz'是不可行的self.key=value
p=Person()
p['name']='za'
print(p['name'])
对于setitem来说:
class Person:def __init__(self):self.cache = {}def __setitem__(self, key, value): #使p['name']='sz'是可行的 使p.name='sz'也是可行的self.cache[key] = valuedef __getitem__(self, item):return self.cache[item]def __delitem__(self, key):del self.cache[key]
p=Person()
p['name']='za' #如果是setattr就会报错
print(p['name'])
del p['name']
setitem主要与切片和索引相关:
#切片:
class Person:def __init__(self):self.items = [1,2,3,4,5,6,7,8]def __setitem__(self, key, value):if isinstance(key,slice):self.items[key]=value#或者self.items[key.start:key.stop:key.step]=valuedef __getitem__(self, item):print(item)def __delitem__(self, key):print(key)
p=Person()
p[0:4:2] = ['a','b']
print(p.items)