Storage类

简介

Storage类是dict的子类,由框架自带。

用Storage类的of静态方法,可以将Model对象转化为Storage对象。

原理

class Storage(dict):
    """
    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
        Traceback (most recent call last):
            ...
        AttributeError: 'a'
        >>> o = Storage(a=1, b=2, c=3) - 'a' - ['b', 'c']
        >>> len(o)
        0
    """

    def __getattr__(self, key):
        ...

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

    def __delattr__(self, key):
        ...

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

    def __sub__(self, other):
        ...

    @staticmethod
    def of(object):
        result = Storage()
        for name in get_type_hints(object).keys():
            result[name] = getattr(object, name)
        return result