我想在腌制对象实例(发送到 json-api 端点)时隐藏一些(私有)属性。我为此添加了一个 __getstate__ 函数,但副作用是 deepcopy 也使用了 __getstate__。我不想在对实例进行深度复制时排除任何属性,有没有办法在这里区分调用函数?
class LevelMixin(object):
def __init___(self...):
....
def __getstate__(self):
"""
If pickleable hide all private and weak refs.
"""
if not getattr(self, '_unpickleable', True):
__state = self.__dict__.copy()
keep_private = ['_unpickleable', 'unpickleable']
state = {}
for k, v in __state.items():
if v is not None and v != "None" and k not in keep_private and not callable(v):
if k.startswith('_') and not k.startswith('__'):
state[k[1:]] = v # if key starts with single underscore, remove it
else:
state[k] = v
else:
state = self.__dict__.copy()
return state
检查堆栈告诉我“deepcopy”或“_flatten_obj_instance”何时是调用函数,但我知道在生产代码中检查这些不是好习惯。关于如何避免使用此代码进行 deepcopy,但在 jsonpickle 中使用它的任何想法?