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

时间:2023-03-09 20:11:37
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 的功能。