Chinaunix首页 | 论坛 | 博客
  • 博客访问: 629624
  • 博文数量: 149
  • 博客积分: 3901
  • 博客等级: 中校
  • 技术积分: 1558
  • 用 户 组: 普通用户
  • 注册时间: 2009-02-16 14:33
文章分类

全部博文(149)

文章存档

2014年(2)

2013年(10)

2012年(32)

2011年(21)

2010年(84)

分类:

2010-05-24 12:01:04

原文 : (有小部分修改)



不做过多解释 ,直接看代码 :
> cc={"x1":{"y2":"z3"}}
> d = AttrDict(cc)

> print cc
{"x1":{"y2":"z3"}}

> d.x1.y2
z3

> d.x.y = 2
> print d.x.y
2

> not d.hehe.x
True
> not d.x.y
False


> d.x.keys()
['y']


#!/usr/bin/python
#encoding: utf-8
class AttrDict(dict):
    """A dictionary with attribute-style access. It maps attribute access to
    the real dictionary. "
""
    def __init__(self, init={}):
        init = init.copy()
        for k in init.keys() :
            if type(init[k]) == type({}) : init[k] = AttrDict(init[k])
        dict.__init__(self, init)

    def __getstate__(self):
        return self.__dict__.items()

    def __setstate__(self, items):
        for key, val in items:
            if type(val) == type({}) : val = AttrDict(val)
            self.__dict__[key] = val

    def __repr__(self):
        return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self))

    def __setitem__(self, key, value):
        if type(value) == type({}) : value = AttrDict(value)
        return super(AttrDict, self).__setitem__(key, value)

    def __getitem__(self, name):
        if not super(AttrDict, self).has_key(name) :
            super(AttrDict, self).__setitem__(name,AttrDict({}))
        return super(AttrDict, self).__getitem__(name)

    def __delitem__(self, name):
        return super(AttrDict, self).__delitem__(name)

    __getattr__ = __getitem__
    __setattr__ = __setitem__
    def copy(self):
        ch = AttrDict(self)
        return ch







阅读(756) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~