copies of classes in python
Assume I have an instance foo of some class Class with some variable foo.x. Now I want to produce a copy of foo:
bar = foo
when I now change bar.x, this also changes foo.x. How can I get a copy of foo, wher开发者_Go百科e I can change everything without changing the original foo? Creating a new instance of Class is not an option, because I need it in the state in which foo already is.
You need to use the module copy.
bar = copy.deepcopy(foo)
You can use deepcopy
:
bar = deepcopy(foo)
Note that you can also implement your own copy with customized(sure if you really need this) behavior the following way:
from copy import copy
class d(object):
def __copy__(self):
newd = d()
newd.x = self.x+1
return newd
foo = d()
foo.x = 11
a = copy(d)
print a.x, foo.x
bar = copy.copy(foo) # make a shallow copy of foo
bar = copy.deepcopy(foo) # make a deep copy of foo
copy(x) Shallow copy operation on arbitrary Python objects.
deepcopy(x, memo=None, _nil=[]) Deep copy operation on arbitrary Python objects.
精彩评论