python对象转字典

1.基础实现

 class TestDict:
name = "wyb"
age = "" def __init__(self):
self.gender = 'male' def keys(self): # 获取字典的键
s = ('name', 'age', 'gender')
return s def __getitem__(self, item): # 获取键对应的值
return getattr(self, item) # getattr获取对象下某个属性的值 o = TestDict()
print(dict(o)) # 创建字典 -> 先调用对象下的keys方法再用o["xxx"]获取值([]本质上是调用对象下的__getitem__方法)

2.进阶实现

 class Base(object):
def __init__(self):
self.fields = [] def __getitem__(self, item):
return getattr(self, item) def keys(self):
return self.fields def hide(self, *keys): # 隐藏域
for key in keys:
self.fields.remove(key)
return self def append(self, *keys): # 添加域
for key in keys:
self.fields.append(key)
return self class Sx(Base):
name = "wyb"
age = 21 def __init__(self):
super(Base, self).__init__()
self.gender = 'male'
# self.fields定义默认输出字段
self.fields = ["name", "age"] o1 = Sx()
print(dict(o1))
o2 = Sx()
print(dict(o2.hide("age")))
o3 = Sx()
print(dict(o3.append("gender"))) # 输出结果:
# {'name': 'wyb', 'age': 21}
# {'name': 'wyb'}
# {'name': 'wyb', 'age': 21, 'gender': 'male'}
上一篇:[POJ2594] Treasure Exploration(最小路径覆盖-传递闭包 + 匈牙利算法)


下一篇:Chrome开发者工具详解(3)-Timeline面板