0

I understand that if I pass a variable as an argument to a function it can only change the value of that argument within its own scope, not the value of the variable at the global scope.

However, this doesn't seem to apply to passing user-defined class instances to a function, where I am able to modify that object in the global scope without a return statement in the function.

For example, in the code below I would have expected the function bar() to only modify the values within the scope of the function, and not change the 'my_class_object' instance of foo in the global scope. However, when I run bar() I find that the value of my_class_object.the_value changes from 0 to 1.

class foo():
    def __init__(self,num):
        self.the_value = num
        
        
def bar(a,b):
    a.the_value +=1
    b +=1
    
    
my_class_object = foo(0)
int_class_object = 0
    
bar(my_class_object,int_class_object)

print(my_class_object.the_value)
print(int_class_object)
  • I think you might have a good explanation here: https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value/430958#430958 – blurfus Mar 16 '21 at 16:39
  • 1
    "I understand that if I pass a variable as an argument to a function it can only change the value of that argument within its own scope" no, this is absolutely incorrect. The fundamental thing to understand is you *pass objects as arguments*. Objects are either mutable or immutable. If an object is mutable, you can modify that object *anywhere* and you can see that change anywhere that object is referenced. This has nothing to do with user-defined objects or built-in objects. All user-defined objects are mutable, though – juanpa.arrivillaga Mar 16 '21 at 18:24
  • To supplement juanpa's comment, the second argument to `bar` is an int which is immutable. Change that to a list and try to `append` and see that it changes as well in the "global" scope – Tomerikoo Mar 16 '21 at 20:26
  • Thank you for your answers. I have also been guided to more information here: https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference, which might also help others who have been confused in the same way. – will_letton Mar 19 '21 at 07:57

0 Answers0