码迷,mamicode.com
首页 > 编程语言 > 详细

python - __setitem__/__getitem__/__delitem__类的内置方法

时间:2018-10-14 00:34:25      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:att   get   attr   item   方式   python   int   pytho   print   

 

# class 内置方法:
# __setitem__
# __getitem__
# __delitem__

class Test():
    X = 100

    def __getitem__(self, item):
        print("getitem")

    def __setitem__(self, key, value):
        print("setitem")

    def __delitem__(self, key):
        print("delitem")

xx = Test()

#通过字典的方式访问类的属性,触发getitem方法
print(xx[X])

#通过字典的方式设置类的属性,触发setitem方法
xx[X] = 200

#通过字典的方式删除类的属性,触发delitem方法
del xx[X]

# 结尾:
# 通过点的方式访问类属性或者修改删除,那么触发类的attr的内置方法
# 而通过字典的方式访问类或者修改删除,那么触发类的item的内置方法

 

python - __setitem__/__getitem__/__delitem__类的内置方法

标签:att   get   attr   item   方式   python   int   pytho   print   

原文地址:https://www.cnblogs.com/Anec/p/9784677.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!