Python 的 setitem、getitem、delitem 特殊方法使用


簡介

setitem:當屬性被以索引方式賦值的時候會調用該方法

getitem:一般如果想使用索引訪問元素時,就可以在類中定義這個方法

delitem:當使用索引刪除屬性時調用該方法

實例

__Author__ = "Lance#"

# -*- 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

上一篇文章中,以 MIMEText 對象構造的 msg 就賦有該屬性,使之具有 msg['From'] = xxx 的功能。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM