skypaladin 发表于 2015-11-30 09:58:16

python中如何用访问属性的方式访问字典中的元素

  在python中访问字典中的元素都是通过下标,但是通过某些方式,我们可以像访问成员变量那样访问字典:
  

a = {  'foo': 1,
  'bar': 2
  
}
  

  
print a.foo
  
print a.bar
  

setattr和__getattr__的使用
  看如下的代码:
  

# coding: utf-8  

  
class Test(object):
  

  def __init__(self):
  self.a = 1
  self.b = 2
  

  # 设置属性都会调用
  def __setattr__(self, key, value):
  print '__setattr__: %s' % key
  self.__dict__ = value
  

  #__getattr__ 只有在访问不存在的成员时才会被调用
  def __getattr__(self, key):
  print '__getattr__: %s' % key
  return self.__dict__
  

  

  
if __name__ == '__main__':
  

  t = Test()
  print t.a
  print t.b
  

  t.c = 12
  print t.c
  t.c = 13
  t.a = 123
  print t.d
  

  setattr是每次设置属性时都会调用,而__getattr则只有当访问不存在的元素时才会调用。
  对象的属性均保存在dict这个字典中。默认的setattr和getattr__也是访问这个字典。

通过一个Storage类的包装访问字典
  

#!/usr/bin/env python  
# coding: utf8
  
import json
  

  
class Storage(dict):
  def __init__(self, *args, **kw):
  dict.__init__(self, *args, **kw)
  

  def __getattr__(self, key):
  return self
  

  def __setattr__(self, key, value):
  self = value
  

  def __delattr__(self, key):
  del self
  

  
if __name__ == '__main__':
  l = {'foo': 'bar'}
  s = Storage(l)
  print s.foo
  print s['foo']
  

  我们可以看到,经过Storage类的包装,此时不仅可以通过下标s['foo'],还可以使用s.foo来调用foo对应的元素。
  原理很简单,我们改变了Storage默认的__getattr和setattr实现,默认实现是访问内部的dict__,而该邂逅访问的是基类dict,所以访问s.foo时,访问的是内部的dict['foo'],所以能访问到元素。

json库loads中的object_hook参数的使用
  看如下的代码,常规的json序列化和反序列化是这样做:
  

import json  
from decimal import *
  

  
obj = {'name': 'haha', 'age': 23, 'height': 1.75}
  

  
json_string = json.dumps(obj)
  
print json_string
  
new_obj = json.loads(json_string)
  
print new_obj
  

  我们从上面看到,dict经过包装,可以改造成Storage,使用访问属性的方式访问元素。json的loads功能也提供了类似的功能。
  

# coding: utf-8  
import json
  

  
obj = {'name': 'haha', 'age': 23, 'height': 1.75}
  
json_string = json.dumps(obj)
  

  
from collections import namedtuple
  
Student = namedtuple('Student',['name', 'age', 'height'])
  

  
def object_hook_handler(dict_obj):
  return Student(name=dict_obj['name'],
  age=dict_obj['age'],
  height=dict_obj['height'])
  

  
new_obj = json.loads(json_string, object_hook=object_hook_handler)
  
print new_obj
  

  打印结果为:
  

Student(name=u'haha', age=23,>  

  可以看到,通过object_hook这个参数传入一个函数,将dict改造成一个有名元组。
  其实,在python中,类也可以看做一个函数,所以直接传入类名做参数即可。
  

from collections import OrderedDict  
new_obj = json.loads(json_string, object_hook=OrderedDict)
  

  
print new_obj
  

  输出结果为:
  

OrderedDict([(u'age', 23), (u'name', u'haha'), (u'height', 1.75)])  

隐藏Storage
  为了使用方便,最好不让用户接触到Storage,所以可以这样写:
  

#!/usr/bin/env python  
# coding: utf8
  
import json
  

  

  
class Storage(dict):
  def __init__(self, *args, **kw):
  dict.__init__(self, *args, **kw)
  

  def __getattr__(self, key):
  return self
  

  def __setattr__(self, key, value):
  self = value
  

  def __delattr__(self, key):
  del self
  

  

  
def storage_object_hook(dct):
  return Storage(dct)
  

  

  
def json_decode(data, *args, **kw):
  return json.loads(data, object_hook=storage_object_hook, *args, **kw)
  

  

  
def json_encode(data, *args, **kw):
  return json.dumps(data, *args, **kw)
  

  

  
if __name__ == '__main__':
  
  l = {'foo': 'bar'}
  l = json_decode(json_encode(l))
  print l
  print l.foo
  
页: [1]
查看完整版本: python中如何用访问属性的方式访问字典中的元素