python 魔术方法:__getitem__、__setitem__、__delitem__、__len__
可以通过__getitem__、__setitem__、__delitem__、__len__ 等方法使类拥有了通过下标来索引的能力。
>>> class Test: def __init__(self): self._dic = {}; def __getitem__(self,key): return self._dic.get(key); def __setitem__(self,key,value): self._dic.setdefault(key,value) def __len__(self): return len(self._dic) >>> >>> d = Test() >>> d['name'] = 'zval' >>> d <__main__.Test object at 0x041938B0> >>> d['age'] = 100 >>> d['name'] 'zval' >>> d['age'] 100
__getattr_ __setattr__像访问类属性一样访问dict中的键值对。
>>> class Adict(dict): def __init__(self,indict={}): dict.__init__(self,indict) def __getattr__(self,item): try: return self.__getitem__(item) except KeyError: pass return None def __setattr__(self,item, value): return dict.__setattr__(self, item, value) >>> d = Adict() >>> d.name = 'zval' >>> d.age=100 >>> d {} >>> d.name 'zval' >>> d.age 100 >>>