0

Problem with assignment of a module variable in a class function

How can I assign a copy of a module variabile in the class function? When I assign this module variable to the class function as self.variable = variable, the module variable is also changed when I make changes with self.variable.

1st Jul 2024, 11:10 PM
Giovanni Paolo Balestriere
Giovanni Paolo Balestriere - avatar
3 Respostas
+ 2
I am not sure if I understand you right but if you have mutable variables like a list. You can use the copy command like that: a = [1,2,3] b = a.copy() b[1] = 5 print(a, b) Btw. if you write class methods, it's a good idea to write cls instead of self. Like here: https://www.sololearn.com/learn/o-JUMP_LINK__&&__Python__&&__JUMP_LINK/2473/?ref=app
2nd Jul 2024, 3:10 AM
Stefanoo
Stefanoo - avatar
+ 1
It would be helpful to show your code, how the class is coded, how you use it and give example of inputs and expected outputs.
2nd Jul 2024, 1:09 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 1
# Hi Giovanni Paolo Balestriere, # If your object that you want to copy contains mutable objects, # such as a list within a list, and you want to completely decouple # it from external changes, use deepcopy from the copy module: import copy a = [1, 2] b = [5, 6, [a]] c = b.copy() d = copy.deepcopy(b) b[1] = 77 a.append(99) print(f"{a = }") # -> a = [1, 2, 99] print(f"{b = }") # -> b = [5, 77, [[1, 2, 99]]] print(f"{c = }") # -> c = [5, 6, [[1, 2, 99]]] print(f"{d = }") # -> d = [5, 6, [[1, 2]]] # https://sololearn.com/compiler-playground/cZtHpXIeJXO7/?ref=app
2nd Jul 2024, 10:07 AM
Per Bratthammar
Per Bratthammar - avatar