class Foo:
def __init__(self, name):
self.name = name
def __getitem__(self, item):
print('===>', self.__dict__[item])
def __setitem__(self, key, value):
self.__dict__[key] = value
def __delitem__(self, key):
print('del obj[key]时,我执行')
self.__dict__.pop(key)
def __delattr__(self, item):
print('del obj.key时,我执行')
self.__dict__.pop(item)
f1 = Foo('a')
f1['age'] = 18
f1['age1'] = 19
del f1.age1
del f1['age']
# setitem
f1['name'] = 'a'
# getitem
f1['name']
delattr:
del f1.name触发delattr;
delitem:
del f1[‘name’]触发delitem;
能写成f1[‘name’]的分为两种情况:
- 字典
- def __setitem__(self) : pass