1. 程式人生 > >python中__getitem__, __setitem__, __delitem__的使用

python中__getitem__, __setitem__, __delitem__的使用

參考: 伯樂地址

用於索引操作,如字典。以上分別表示獲取、設定、刪除資料

#Python __doc__
class C(object):
    """ Holy Shit What The Fuck """
    def __init__(self):
        self.value = {}
        self.name = 'WuPeiQi'

    def __getitem__(self, item):
        print '__getitem__', item
        return self.value[item]

    def __setitem__
(self, key, value):
print '__setitem__', key, value self.value[key] = value def __delitem__(self, key): print '__delitem__', key del self.value[key] def __len__(self): return len(self.value) print C.__doc__ c = C() #print c #result = c['k1'] c['k2'] = 5
c['k1'] = "Hello" print c['k2'] print len(c)