Reputation: 27
In class, let's say I have an instance
self.my_instance=6
Then, in a method, say I have something like
my_variable=self.my_instance
Every time I change my_variable
to some other value, self.my_instance
changes its value also, and this is not what I want. I want to modify my_variable
without affecting self.my_instance
. This can be quite frustrating and confusing in large programs too.
Thank you!
Upvotes: 0
Views: 1047
Reputation: 20336
When you say my_variable = self.myinstance
, my_variable
is now just an alias to the object that self.myinstance
refers to. To make it a separate object, you can use slicing:
my_variable = self.myinstance[:]
Using self.myinstance[:]
means to take all objects from the beginning to the end which means everything. Since it is a slice, however, it returns a copy so this is a common way to get a copy of a list.
This works in your case because my_variable
is a list, but if it is a dictionary, for instance, you can use the copy
module:
import copy
my_variable = copy.copy(self.myinstance) # Shallow copy
or
my_variable = copy.deepcopy(self.myinstance) # Deep copy
Dictionaries also have the .copy()
method for shallow copies.
Upvotes: 2