__getitem__\__setitem__\__delitem__


class Foo(object):
def __init__(self):
self.data = {}
def __getitem__(self, key):
print('__getitem__', key)
return self.data.get(key)
def __setitem__(self, key, value):
print('__setitem__', key, value)
self.data[key] =value
def __delitem__(self, key):
print('__delitem__', key)


obj = Foo()
obj['name'] = "alex"
# print(obj['name'])
# print(obj.data)
del obj["sdfdsf"]
# result = obj['k1'] # 自动触发执行 __getitem__
# obj['k2'] = 'alex' # 自动触发执行 __setitem__
# del obj['k1']

__setitem__ name alex
__delitem__ sdfdsf

posted @ 2018-11-15 20:29  rongye  阅读(124)  评论(0编辑  收藏  举报