I'm having trouble understanding why when a local variable in a class function is updated, the same variable in the calling function also changes.
In this simple example, when class_func
is called, it will take from the parent func
the variable my_var, and in each instance my_var will be back to []
.
But after the first time c.class_func
is called, my_var
in the function func
is changed. And I don't understand why that would be?
Appreciate any insight.
class my_class :
def class_func(self, my_var):
if my_var == [] :
my_var += [1]
def func (classes, my_var) :
for c in classes :
print(my_var)
c.class_func(my_var)
print(my_var)
class1 = my_class()
class2 = my_class()
func(classes=[class1, class2], my_var=[])
Output:
[]
[1]
[1]
[1]