How to keep attribute outside __dict__?
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 o开发者_StackOverflowutside 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.
Add some prefix for attributes you don't want to save and exclude them while saving.
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.
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:
class Coordinate(object):
def __init__(self, x, y, z=0):
self.x, self.y, self.z = x, y, z
def __getstate__(self):
"""By default if no __getstate__ was defined __dict__ will be pickle, but in
this case i don't want to pickle self.z attribute because of that this
method return a dict in the form {'x': ..., 'y': ...}.
"""
return {
"x": self.x,
"y": self.y,
}
def __setstate__(self, data):
self.__init__(data["x"], data["y"])
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.
精彩评论