如何将属性保留在 __dict__ 之外?
我正在创建一系列对象实例,我使用它们的 __dict__ 属性保存和加载它们的属性。我想将一些属性保留在 __dict__
之外,只是因为我不希望保存或加载它们。
更具体地说:
我创建了一个仅包含子对象列表的父对象。子对象的 __dict__
被保存到文件中并稍后加载以再次实例化它们。我希望子对象具有对父对象的引用,但我不希望将该引用保存到文件中,也不希望从文件中加载,因为它没有意义。
是否有任何语法可以从 __dict__
中排除该属性?
PS:许多答案建议使用 pickle,我目前使用 json 来保持数据可读。 EM>
I am creating a series of object instances, the attributes of which i save and load using their __dict__
attribute. I would like to keep some attributes outside of __dict__
, simply because i do not want them to be saved or loaded.
More specifically:
I created a parent object merely holding a list of children objects. Children objects' __dict__
is saved to file and loaded later on to instantiate them again. I want the children objects to have a reference to the parent, but i do not want that reference to be saved to, nor loaded from file, as it would not make sense.
Is there any syntax that would exclude the attribute from __dict__
?
PS: many answers suggest using pickle, i am currently using json to keep data human readable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为您不想保存的属性添加一些前缀,并在保存时排除它们。
Add some prefix for attributes you don't want to save and exclude them while saving.
这种方法行不通,因此无法解决您的问题。相反,您应该扩展框架以允许您指定要从保存/加载中省略哪些属性。
然而,您没有使用已经提供此类功能的内置持久性技术之一(例如 pickle)似乎很奇怪。
This approach won't work and so is not going to solve your problem. You should instead extend your framework to allow you to specify which attributes were to be omitted from the save/load.
However, it seems odd that you aren't using one of the built in persistence techniques, e.g. pickle, that already offer such features.
如果您使用 python pickle 您可以创建两个方法
__getstate__
和__setstate__
允许您自定义属性像这样泡菜:If you are using python pickle you can create the two method
__getstate__
and__setstate__
that will allow you to customize the attribute to pickle like so:您可以重写对象的
__getattr__
和__setattr__
方法,以向__dict__
隐藏您的属性。但您需要将附加属性存储在其他地方。它还使得很难弄清楚你的对象真正拥有哪些成员。所以这更像是一种黑客行为,而不是一个好的解决方案。You can override the
__getattr__
and__setattr__
methods of your object to hide your attributes from__dict__
. But you need to store your additional attributes somewhere else. Also it makes it very hard to figure out which members your object really has. So it is more a hack than a good solution.