• 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 的功能。

  • 相关阅读:
    字符串与Json操作
    默认让IE用最高文档模式浏览网页
    MVC中简单的文件下载代码
    2017年1月22日
    JDK环境变量设置
    如何实现windows命令提示符的tab补全
    win7热点设置
    为什么小米5不能适配win7
    各种错误锦集
    插头DP
  • 原文地址:https://www.cnblogs.com/GyForever1004/p/8972092.html
Copyright © 2020-2023  润新知