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

  • 相关阅读:
    CSP2019题解
    [NOI2019]弹跳(KD-Tree)
    集合框架面试题
    注解
    WiFi攻防
    简单完整讲述Servlet生命周期
    Java多线程
    Java--面向对象讲解
    layUi
    java提高篇(三)-----理解java的三大特性之多态
  • 原文地址:https://www.cnblogs.com/GyForever1004/p/8972092.html
Copyright © 2020-2023  润新知