重写Python中dict __getitem__,角标查询不存

2019-11-12  本文已影响0人  晴茗
class Storage(dict):
    """
    from web2py
    A Storage object is like a dictionary except `obj.foo` can be used
    in addition to `obj['foo']`.

        >>> o = Storage(a=1)
        >>> o.a
        1
        >>> o['a']
        1
        >>> o.a = 2
        >>> o['a']
        2
        >>> del o.a
        >>> o.a
        None
        >>> o['a']
        None
    """

    def __getitem__(self, key):
        try:
            return super(Storage, self).__getitem__(key)
        except KeyError, k:
            return None

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError, k:
            return None

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

    def __delattr__(self, key):
        try:
            del self[key]
        except KeyError, k:
            raise AttributeError, k

    def __repr__(self):
        return '<Storage ' + dict.__repr__(self) + '>'

    def __getstate__(self):
        return dict(self)

    def __setstate__(self, value):
        for k, v in value.items(): self[k] = v

result = {
    "status": 1, "obj_type": 1, "operator_id": 1293589, "operate_time": "2019-03-06 15:18:55", "description": "",
    "creator": "", "dept_name": "\u534e\u4e30\u96c6\u56e2", "id": 315, "number": "0000001", "company_id": 111,
    "dept": {"is_leaf": 0, "adapter_id": "", "abbreviation": "",
             "search_string": "\u534e\u4e30\u96c6\u56e2:hu\u00e1f\u0113ngj\u00edtu\u00e1n:hfjt",
             "credit_code": "000", "approve_code": "", "job_id": "", "outer_emp_count": 0, "company_id": 111,
             "parent_id": "", "fax": "", "operator_id": 1322501, "c_field18": "", "c_field19": "", "postal_address": "",
             "c_field14": "", "c_field15": "", "c_field16": "", "c_field17": "", "c_field10": "", "business_id": "",
             "c_field12": "", "number": "0001", "adapter_parent_id": "", "name": "\u534e\u4e30\u96c6\u56e2", "level": 1,
             "org_type": 10, "job_grade_id": "", "orderno": "", "enabled": True, "org_unit_id": "",
             "full_name": "\u534e\u4e30\u96c6\u56e2", "description": "", "plan_count": 12, "position_parent_id": "",
             "outer_part_count": 0, "entry_exit_records": "", "count_emp": 341, "charge_business": "",
             "compulsory_vacation_days": "",
             "position_description_index": "", "updater_id": "", "outer_info": "", "post_code": "",
             "establishment_date": "2019-01-25", "position_sequence_id": "", "tree_id": "646671", "emp_count": 341,
             "c_field8": "", "c_field9": "", "c_field6": "", "c_field7": "", "c_field4": "", "c_field5": "",
             "c_field2": "", "c_field3": "", "c_field1": "", "dept_type": "", "modify_time": "", "economic_type_id": "",
             "registered_address": "111", "duty": "", "is_work_shift": "", "work_shift_years": "",
             "is_legal_entity": True,
             "registered_country_id": 650254, "org_full_name": "\u534e\u4e30\u96c6\u56e2",
             "extend_count": {"inner_part_count": 0, "plan_count": 0, "sub_inner_part_count": 2,
                              "sub_outer_part_count": 0, "outer_emp_count": 0, "sub_plan_count": 12,
                              "outer_part_count": 0, "count_emp": 0, "sub_count_emp": 341, "sub_outer_emp_count": 0},
             "soft_delete": "", "work_content": "", "charge_person_id": "", "main_post": "", "full_number": "",
             "business_class_id": "", "full_orderno": "", "subordinate_unit_id": "", "plan_manager_org_id": "",
             "c_field20": "", "contract_body_id": "", "id": 646671, "position_type_id": "",
             "is_compulsory_vacation": "", "job_step_id": "", "operate_time": "2019-01-25 08:44:49",
             "need_executive_qualification": "", "position_level_id": "", "invest_class_id": "", "c_field11": "",
             "begin_date": "1903-01-01", "c_field13": "", "inner_part_count": 2, "charge_position_id": "",
             "isleaf": False},
    "create_date": "2019-03-06 00:00:00", "dept_id": 646671, "is_deleted": 1, "template_id": "",
    "name": "\u901a\u7528\u6d4b\u8bd5"}



def convert_to_storage(dict_data):
    storage = Storage()
    for k, v in dict_data.items():
        if not isinstance(v, dict):
            storage[k] = v
        else:
            storage[k] = convert_to_storage(v)
    return storage

aaa = convert_to_storage(result)
print aaa.dept.extend_count.sub_count_emp
print aaa["dept"]["ssa"]
上一篇下一篇

猜你喜欢

热点阅读