I need to define开发者_开发知识库 my own deepcopy function for one of my classes. The documentation says that the function __deepcopy__()
is passed a memo dictionary for tracking which objects have already been copied, to avoid getting caught in coping a recursive object. However it doesn't say what to put in the dictionary. Do I put objects in, or object IDs? How do you use it? I can't find any site that explains it, except this book that says that it need not be used, except to pass it to other invocations of __deepcopy__
.
Thanks
To be consistent with the built-in copy.deepcopy
behavior, you should use the id
of the object as a key.
More Details:
While you can often get away with using a different key scheme (such as the object itself, if it's hashable), as long as you're consistent, you can still run into trouble. Frequently __deepcopy__
is implemented by calling copy.deepcopy
on some contained attributes. If you add items directly to memo
, you have to be certain the keys won't collide with items added by copy.deepcopy
, which adds keys generated by id
, which are integers.
So if you use a different key scheme, such as using objects directly as keys, you can't ever add any integer objects.
Bottom Line:
It's much easier to just use id
and not have to worry about the exceptions above.
To answer my own question, with thanks to @Jon-Eric:
What I understand from the example shown at http://www.doughellmann.com/PyMOTW/copy/, is that you use self
as the key, and the copied object as the value. Then, when it is attempted to copy this object(self
) again, one can check the memo dictionary to see whether it has already been copied, and return the reference to the copy, memo[self]
.
精彩评论