From the copy
documentation:
Classes can use the same interfaces to control copying that they use to control pickling.
[...]
In order for a class to define its own copy implementation, it can define special methods
__copy__()
and__deepcopy__()
So which one is it? __setstate__()
and __getstate__()
that are used when pickling, or __copy__()
and __deepcopy__()
?
It works as follows: if a class defines __copy__
, that takes precedence for copy.copy
purposes (and similarly __deepcopy__
takes precedence for copy.deepcopy
purposes). If these very specific special methods are not defined, then the same mechanisms as for pickling and unpickling are tested (this includes, but is not limited to, __getstate__
and __setstate__
; I've written more about this in my book "Python in a Nutshell" (which @ilfaraone quotes only partially).
__setstate__()
and __getstate__()
.
Notice that the copy documentation says that they can use the same interface, but they don't necessarily have do so.
See this excerpt from Python in a Nutshell, or this explanation on the Python Mailing List.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With