面向对象(__item__)

 1 #Author : Kelvin
 2 #Date : 2019/1/20 21:37
 3 class People:
 4     def __getitem__(self, item):
 5         print("getitem...")
 6         return self.__dict__[item]
 7     def __setitem__(self, key, value):
 8         print("setitem...")
 9         self.__dict__[key]=value
10     def __delitem__(self, key):
11         print("delitem...")
12         del self.__dict__[key]  #等同于 self.__dict__.pop(key)
13 
14 p=People()
15 print(p.__dict__)
16 # 给__dict__添加属性
17 p["name"]="kelvin"
18 p["age"]=18
19 print(p.__dict__)
20 # 获取__dict__对象属性
21 print(p["name"])
22 # 删除__dict__对象属性
23 del p["age"]
24 print(p.__dict__)

也就是给对象__dict__增加属性的一种方式。

原文地址:https://www.cnblogs.com/sun-10387834/p/10299487.html