说明
1、_len_调用len()方法时,就是调用对象内的_len_()方法
2、_getitem_调用object[item]方法时,就是调用对象内的_getitem_()方法,字典专用
3、_setitem_调用object[item]=xxx方法时,就是调用对象内的_setitem_()方法,字典专用
实例
class TestContainer: def __init__(self): self.my_list = [] self.my_dict = {} def __len__(self): return len(self.my_list) def append(self, v): self.my_list.append(v) def __getitem__(self, item): return self.my_dict.get(item) def __setitem__(self, key, value): self.my_dict[key] = value def __delitem__(self, key): del self.my_dict[key] def __contains__(self, item): return True if item in self.my_list else False testContainer = TestContainer() testContainer.append(1) print(len(testContainer)) testContainer["name"] = "xiaoming" print(testContainer["name"]) del testContainer["name"] print(testContainer["name"]) print(1 in testContainer)
本文链接:http://so.lmcjl.com/news/10193/