Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copies of classes in python

Tags:

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, where 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.

like image 851
Till B Avatar asked Aug 30 '26 02:08

Till B


2 Answers

You need to use the module copy.

bar = copy.deepcopy(foo)
like image 177
Rivka Avatar answered Aug 31 '26 15:08

Rivka


You can use deepcopy:

bar = deepcopy(foo)
like image 38
Björn Pollex Avatar answered Aug 31 '26 16:08

Björn Pollex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!