在嵌套对象之间共享值,但不与其他实例共享

时间:2015-07-30 15:18:05

标签: python optimization

我如何在嵌套对象之间共享字符串列表,但不与其他类实例共享。

所以在我的代码中我有:

class A(object):

    def __init__(self):
        self.attr1 = "value1"
        self.son1 = ...  # can be nested structute too.
        self.son2 = ...
        self.son3 = ...

    def dump(self, filter=None):
        #  exclude keys from filter list, json.dumps like method
        pass


a = A()
a.dump(["attr1", "attr2", "attr3"])

b = A()
b.dump()

我想与属于实例a的所有儿子和大儿子分享["attr1", "attr2", "attr3"],其中每个值都可以是属性名称。

谢谢,

[编辑]

这是我的代码片段

class MixinJSONable(object):

    _ignored_json_keys = list()

    @staticmethod
    def append_ignored_keys(keys=None, append=True):
        keys = keys or []
        if append:
            MixinJSONable._ignored_json_keys.extend(keys)
        else:
            MixinJSONable._ignored_json_keys = keys

    def reset_keys(self):
        self.append_ignored_keys(keys=[], append=False)

    def to_dict(self):

        self._jsonable = (int, list, str, float, ComponentIter, Component, GroupComponent)

        _dict = dict()
        for attr in dir(self):
            value = getattr(self, attr)
            if attr.startswith("_") or attr in getattr(MixinJSONable, "_ignored_json_keys", []):
                continue
            elif isinstance(value, self._jsonable) or value is None or hasattr(value, 'to_dict'):
                # to_dict method is used as serialization method.
                value = value
            elif isinstance(value, datetime):
                value = value.strftime("%Y-%m-%d %H:%M:%S")
            else:
                if not callable(attr):
                    json_logger.debug("%s not handled to be jsonable" % attr)
                continue
            _dict[attr] = value
        return _dict

    def to_json(self, **kw):
        """
        Dump object as Json.

        Accept the same keys than :func json.dumps:. If ignored_keys (list) is passed,
        the keys will not be dumped in the json (filter over all sons)

        """
        indent = kw.pop("indent", 4)  # use indent key if passed otherwise 4.
        _ignored_json_keys = kw.pop("ignored_keys", [])
        if _ignored_json_keys:
            MixinJSONable._ignored_json_keys = _ignored_json_keys
        result = json.dumps(self, indent=indent, default=_default_json_encoder, **kw)
        self.reset_keys()
        return result

0 个答案:

没有答案