0

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]
fazistinho_
  • 195
  • 1
  • 11
  • 2
    This has nothing to do with inheritance. You're using the same value of `my_var`, not making a copy of the list. – Barmar Jun 09 '20 at 17:06
  • Isn't the `my_var` in `class_func` local to the function? – fazistinho_ Jun 09 '20 at 17:46
  • my_var that you give in func is passed as a reference to all the function calls. Meaning you always manipulate the original my_var object when modifying the referenced object from the class_func. – Damien LEFEVRE Jun 09 '20 at 17:59
  • understood, so what would be the smarter way to do this? – fazistinho_ Jun 09 '20 at 18:02
  • It's not even clear why you're using classes here. `my_var` is just a local variable, not a class attribute. It would all be the same with ordinary functions. – Barmar Jun 09 '20 at 19:50
  • This isn't my actual function, I just created a simple example to illustrate the problem I was having. My understanding was that a variable defined within a function would not affect variables in another function by the same name. – fazistinho_ Jun 10 '20 at 06:21

0 Answers0