【工具封装】给 Python 字典加上点语法,实现 对象.属性 调用

一、序言:

  今天小编给大家封装了一个魔法工具,用了这个工具就能将 Python 中的字典类型数据,实现对象.属性的语法,开发时使用起来非常方便,还在等什么?赶紧收藏+点赞+关注吧 !!!

---- Nick.Peng

二、实现代码如下:

# -*- coding: utf-8 -*-
# @Author: Nick.Peng
# @Date:   2019-10-23 15:34:08
# @Last Modified by:   Nick.Peng
# @Last Modified time: 2019-10-24 09:49:30

class Struct(dict):
    """
    - 功能:为字典加上点语法,实现 对象.属性 调用。
    - 例如:
    >>> d = Struct({'age':18})
    >>> d.age
    >>> 18
    >>> d.gender
    >>> None
    """

    def __init__(self, dictobj={}):
        self.update(dictobj)

    def __getattr__(self, name):
        # Pickle is trying to get state from your object, and dict doesn't implement it.
        # Your __getattr__ is being called with "__getstate__" to find that magic method,
        # and returning None instead of raising AttributeError as it should.
        if name.startswith('__'):
            raise AttributeError
        return self.get(name)

    def __setattr__(self, name, val):
        self[name] = val

    def __hash__(self):
        return id(self)

你可能感兴趣的:(字典类型加上点语法,实现,对象.属性,调用,Python)