Python 的 setitem、getitem、delitem 方法使用

简介

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
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值