__getitem__,__setitem__,__delitem__
用于索引操作,如字典。以上分别表示获取,设置,删除数据
class Foo(object):
def __getitem__(self, key):
print('__getitem__',key)
def __setitem__(self, key, value):
print('__setitem__',key,value)
def __delitem__(self, key):
print('__delitem',key)
obj = Foo()
# 自动触发执行__getitem__
result = obj['k1'] # __getitem__ k1
# 自动触发执行__setitem__
obj['k2'] = 'laowang' # __setitem__ k2 laowang
# 自动触发执行__delitem__
del obj['k1'] # __delitem k1