1. 程式人生 > >python:__setitem__方法詳解

python:__setitem__方法詳解

__setitem__(self,key,value):

這個方法應該以與鍵相關聯的方式儲存值,以便之後能夠使用__setitem__來獲取。當然,這個物件可變時才需要實現這個方法。

class Tag:
    def __init__(self):
        self.change={'python':'This is python',
                     'php':'PHP is a good language'}

    def __getitem__(self, item):
        print('呼叫getitem')
        return self.change[item]

    def __setitem__(self, key, value):
        print('呼叫setitem')
        self.change[key]=value

a=Tag()
print(a['php'])
a['php']='PHP is not a good language'
print(a['php'])

輸出:

呼叫getitem
PHP is a good language
呼叫setitem
呼叫getitem
PHP is not a good language