1.基础实现
1 class TestDict: 2 name = "wyb" 3 age = "21" 4 5 def __init__(self): 6 self.gender = 'male' 7 8 def keys(self): # 获取字典的键 9 s = ('name', 'age', 'gender') 10 return s 11 12 def __getitem__(self, item): # 获取键对应的值 13 return getattr(self, item) # getattr获取对象下某个属性的值 14 15 16 o = TestDict() 17 print(dict(o)) # 创建字典 -> 先调用对象下的keys方法再用o["xxx"]获取值([]本质上是调用对象下的__getitem__方法)
2.进阶实现
1 class Base(object): 2 def __init__(self): 3 self.fields = [] 4 5 def __getitem__(self, item): 6 return getattr(self, item) 7 8 def keys(self): 9 return self.fields 10 11 def hide(self, *keys): # 隐藏域 12 for key in keys: 13 self.fields.remove(key) 14 return self 15 16 def append(self, *keys): # 添加域 17 for key in keys: 18 self.fields.append(key) 19 return self 20 21 22 class Sx(Base): 23 name = "wyb" 24 age = 21 25 26 def __init__(self): 27 super(Base, self).__init__() 28 self.gender = 'male' 29 # self.fields定义默认输出字段 30 self.fields = ["name", "age"] 31 32 33 o1 = Sx() 34 print(dict(o1)) 35 o2 = Sx() 36 print(dict(o2.hide("age"))) 37 o3 = Sx() 38 print(dict(o3.append("gender"))) 39 40 # 输出结果: 41 # {'name': 'wyb', 'age': 21} 42 # {'name': 'wyb'} 43 # {'name': 'wyb', 'age': 21, 'gender': 'male'}