Pythonのsetitem、getitem、delitemメソッド



Python Setitem Getitem



簡単な紹介

setitem:プロパティがインデックス割り当てにある場合、メソッドを呼び出します



getitem:一般的なインデックスを使用して要素にアクセスする場合は、クラスでメソッドを定義できます

delitem:このメソッドは、インデックスが属性を削除するときに呼び出されます



__Author__ = 'Aliu#' # -*- coding = utf-8 -*- class Point: def __init__(self): pass def __str__(self): return 'Point is (%s,%s)' %(self.x, self.y) def __setitem__(self, key, value): print('Called the __setitem__ function') self.__dict__[key] = value def __getitem__(self, item): print('Called the __getitem__ function') try: if item == 'x': return '%s' %self.x elif item == 'y': return '%s' %self.y except: return 'There is no this item in class Point' def __delitem__(self, key): del self.__dict__[key] if __name__ == '__main__': p = Point() p['x'] = 3 print(p['x']) p['y'] = 6 print(p) del p['x'] print(p['x'])

運転結果

Called the __setitem__ function Called the __getitem__ function 3 Called the __setitem__ function Point is (3,6) Called the __getitem__ function There is no this item in class Point Process finished with exit code 0